You are on page 1of 17

Buttons enable users to interact with your program.

For example, many dialog boxes have an OK button and


a Cancel button. Users can click the OK button to submit the information entered in the dialog box.
Alternatively, they can click Cancel to close the dialog box without submitting any data.
You can set properties of a button to change its appearance. For example, you can set the Text property to
display specific text on a button, or set the ForeColor property to change the color of the text. For more
information, see How to: Create a Non-Rectangular Button.
Controls have events that are raised whenever a user performs a specific action on the control. You can
create event handlers that determine how the program should respond to the event. All controls have a
default event handler, and for a button, it is the Click event. The code that you write in the Click event
handler of the button runs whenever the user clicks the button.

To use buttons in a program


1.
2.
3.
4.
5.
6.
7.
8.

9.

On the File menu, click NewProject.


In the New Project dialog box, in the Templates pane, click Windows Forms Application.
In the Name box, type ButtonExample, and then click OK.
A new Windows Forms project opens.
From the Toolbox, drag a Button onto the form.
In the Properties window, change the Text property to read: Display Date and then press ENTER.
In the Properties window, click the drop-down arrow to the right of the ForeColor property, and
then click the Custom tab of the dialog box that opens.
Click the red box to apply red font to the text of the button.
In the form, double-click the button to open the Code Editor.
The Code Editor opens in the middle of a method named button1_Click. This is the Click event
handler. The code you write here will execute when the button is clicked.
In the button1_Click event handler, type the following line of code.

C#

Copy Code

MessageBox.Show("Today is " +
DateTime.Today.ToLongDateString());
10.
11.

Press F5 to run your program.


The program starts and the form appears. When you click the Button, a message box displays
today's date.

How to: Call a Button's Click Event Programmatically


Even if a user does not click a button, you can raise the button's Click event programmatically by using the
PerformClick method. The following example demonstrates how to call the click event of a button within a
program. When button2 is clicked, the click event for button1 is also triggered.

To use buttons in a program


1.
2.

3.
4.
5.

On the File menu, click NewProject.


In the New Project dialog box, in the Templates pane, click Windows Forms Application, and
then click OK.
A new Windows Forms project opens.
From the Toolbox, drag two Button controls onto the form.
In the form, double-click the first button (button1) to create the Click event handler.
In the button1_Click event handler, type the following line of code.

C#

Copy Code

MessageBox.Show("button1.Click was raised.");


6.
7.

Right-click the code, and then click View Designer.


Double-click the second button (button2) to create the Click event handler.

8.

In the button2_Click event handler, type the following line of code.

C#

Copy Code

// Call the Click event of button1.


test.PerformClick();
9.
10.

Press F5 to run the program.


The program starts and the form appears. When you click either button1 or button2, the click
event handler of button1 displays a message.

How to: Display Text on a Windows Form


You can display text on a variety of controls, but the primary control for displaying text in your program is
the Label control. When you add a label to a form, the background appears in the same color as the form so
that only the text is visible. You can also change the BackColor property of the label.
You can display text in the label by setting its Text property. The Font property determines the display font
for the text in the Text property. The ForeColor property determines the color of the text itself.

To display text in a label


1.
2.
3.
4.

5.

On the File menu, click NewProject.


In the New Project dialog box, click Windows Forms Application, and then click OK.
A new Windows Forms project opens.
From the Toolbox, drag a Label onto the form.
Add a Button control to the form, and change the following properties:

Property

Value

Name

changeText

Text

Change Text

Size

80, 23

Double-click the button to create the changeText_Click event handler, and add the following
code:

C#

Copy Code

this.label1.Text = "Time " +


DateTime.Now.ToLongTimeString();
6.

7.

Add another Button control to the form, and change the following properties

Property

Value

Name

changeColor

Text

Change Color

Size

80, 23

Double-click the button to create the changeColor_Click event handler, and add the following
code:

C#

Copy Code

Random randomColor = new Random();


2

this.label1.ForeColor =
Color.FromArgb(randomColor.Next(0, 256),
randomColor.Next(0, 256), randomColor.Next(0,
256));
8.
9.
10.

Press F5 to run the program.


Click Change Text and verify that the text in the label is updated.
Click Change Color and verify that the font of the text is changed to a new color.

How to: Use TextBox Controls to Get User Input


You can both display text and retrieve text from users by using a TextBox control. After a user types data in
a TextBox, you can retrieve this data by using the Text property. By default, the Multiline property of the
TextBox is set to false. This means that users cannot press the ENTER key to create multiple lines of text in
the TextBox. You can set the Multiline property to true to enable this.

To retrieve input typed in a text box


1.
2.
3.

4.

5.

On the File menu, click NewProject.


In the New Project dialog box, click Windows Forms Application, and then click OK.
A new Windows Forms project opens.
From the Toolbox, drag a TextBox control onto the form, and change the following properties in
the Properties window:

Property

Value

Name

inputText

Multiline

True

Size

175, 90

Add a Button control next to the text box, and change the following properties:

Property

Value

Name

retrieveInput

Text

Retrieve

Double-click the button to create the retrieveInput_Click event handler, and add the following
code:

C#

Copy Code

MessageBox.Show(this.inputText.Text);
6.
7.
8.

Press F5 to run the program.


Type multiple lines of text in the text box, and then click Retrieve.
Verify that the message displays all the text that you typed in the text box.

How to: Convert the Text in a TextBox Control to an Integer


When you provide a TextBox control in your application to retrieve a numeric value, you often have to
convert the text (a string) to a numeric value, such as an integer. This example demonstrates two methods
of converting text data to integer data.

Example

C#

Copy Code

int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);
Compiling the Code
This example requires:

A TextBox control named textBox1.

Convertirea textului dintr-un control de tip TEXBOX in Integer


(exemple pentru variantele de mai sus)
Aveti nevoie de un 2 controale de tip TEXBOX i un control de tip Buton
private void button1_Click(object sender, EventArgs e)
{
int intreg1, intreg2, intreg3;
intreg1=Convert.ToInt32(textBox1.Text);
intreg2=Convert.ToInt32(textBox2.Text);
intreg3 = intreg1 + intreg2;
textBox3.Text = Convert.ToString(intreg3);
MessageBox.Show(Convert.ToString(intreg3));
}

sau varianta
private void button1_Click(object sender, EventArgs e)
{
int intreg1, intreg2, intreg3;
string cuvint;
intreg1=Convert.ToInt32(textBox1.Text);
intreg2=Convert.ToInt32(textBox2.Text);
intreg3 = intreg1 + intreg2;
cuvint = Convert.ToString(intreg3);
textBox3.Text =cuvint;
MessageBox.Show(cuvint);
}
private void button1_Click(object sender, EventArgs e)
{
int intreg1, intreg2, intreg3;
string cuvint;
intreg1=int.Parse(textBox1.Text);
intreg2=int.Parse(textBox2.Text);
intreg3 = intreg1 + intreg2;
cuvint = Convert.ToString(intreg3);
textBox3.Text =cuvint;
MessageBox.Show(cuvint);
}

La executie se introduc numere (incercati si text) n Textbox1


i Texbox2, se aduna si rezultatul apare in MessageBox i n
Texbox3
Robust Programming
The following conditions may cause an exception:

The text converts to a number that is too large or too small to store as an int.

How to: Set the Selected Text in a TextBox Control


This example programmatically selects text in a Windows Forms TextBox control and retrieves the selected
text.

Example

C#

Copy Code

private void button1_Click(object sender, EventArgs e)


{
textBox1.Text = "Hello World";
textBox1.Select(6, 5);
MessageBox.Show(textBox1.SelectedText);
}
Compiling the Code
This example requires:

A form with a TextBox control named textBox1 and a Button control named button1. Set the

Click event handler of button1 to button1_Click.

Note:
The code can also be used with a RichTextBox control by
substituting a RichTextBox control named richTextBox1 for the
TextBox control and changing the code from textBox1 to
richTextBox1.
Robust Programming
In this example you are setting the Text property before you retrieve the SelectedText value. In most
cases, you will be retrieving text typed by the user. Therefore, you will want to add error-handling code in
case the text is too short.

How to: Format Characters in a RichTextBox Control


This example writes a sentence, which contains three words in three different font styles (bold, italic, and
underlined), to an existing RichTextBox control.

Example

C#

Copy Code

richTextBox1.Rtf = @"{\rtf1\ansi This text is in \b


bold\b0, " +
@"this is in \i italics\i0, " +
@"and this is \ul underlined\ul0.}";

Compiling the Code


This example requires:
A RichTextBox control named richTextBox1.

Robust Programming
The rich text format is very flexible, but any errors in the format lead to errors in the displayed

How to: Load Text into a RichTextBox Control


This example loads a text file that a user selects in the OpenFileDialog. The code then populates a
RichTextBox control with the file's contents.

Example

C#

Copy Code

// Create an OpenFileDialog object.


OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the filter to look for text files.
openFile1.Filter = "Text Files|*.txt";
// If the user selected a file, load its contents into
the RichTextBox.
if (openFile1.ShowDialog() ==
System.Windows.Forms.DialogResult.OK)
richTextBox1.LoadFile(openFile1.FileName,
RichTextBoxStreamType.PlainText);
Compiling the Code
This example requires:

A RichTextBox control named richTextBox1. Insert the code segment into the Form1_Load
method

How to: Display a Color Pallet


You can use the built-in ColorDialog component to display a color dialog box instead of creating your own
color pallet. For example, you can enable users to select a color to apply to a Windows form when they click
a button on the form.

To display the color dialog box


1.
2.
3.

On the File menu, click New Project.


The New Project dialog box appears.
Click Windows Forms Application and then click OK.
From the Toolbox, drag a Button control to the form, and change the following properties in the
Properties window:

Property

Value

Name

formColor
6

Text
4.

Color

Drag a ColorDialog component from the Dialogs tab of the Toolbox to the form.

colorDialog1 appears in the component tray.


5.
6.

Double-click the Color button to create the default event handler in the Code Editor.
In the formColor_Click event handler, add the following code to display the color dialog box and
change the background color of the form according to the user's choice.

C#

Copy Code

if (colorDialog1.ShowDialog() == DialogResult.OK)
{
this.BackColor = colorDialog1.Color;
}
7.
8.
9.
10.

Press F5 to run the code.


When the form opens, click Color, click a color in the resulting dialog box, and then click OK.
Verify that the chosen color is applied to the form.
Close the application.

How to: Browse a Folder


You can use the built-in FolderBrowserDialog component to enable users to browse a folder. To display a
dialog box, you use the ShowDialog method. You can then check whether the user clicked the OK button by
using the DialogResult.OK field.

To display the folder browser dialog box


1.
2.
3.
4.

5.

On the File menu, click New Project.


The New Project dialog box appears.
Click Windows Forms Application and then click OK.
Add a Label control to the form, and use the default name, Label1.
Add a Button control to the form, and change the following properties in the Properties window:

Property

Value

Name

folderPath

Text

Path

Drag a FolderBrowserDialog component from the Dialogs tab of the Toolbox to the form.

folderBrowserDialog1 appears in the component tray.


6.
7.

Double-click the button to create the default event handler in the Code Editor.
In the folderPath_Click event handler, add the following code to display the folder browser
dialog box and display the selected path in the label.

C#

Copy Code

if (folderBrowserDialog1.ShowDialog() ==
DialogResult.OK)
{
this.label1.Text =
folderBrowserDialog1.SelectedPath;
}
8.
9.
10.

Press F5 to run the code.


When the form appears, click Path, click a folder in the list, and then click OK.
Verify that the selected path appears in the label.

11.

Close the application.

How to: Display a List of Fonts


You can use the built-in FontDialog component to display a selection of fonts instead of creating your own
font dialog box. For example, you can enable users to select a font in the dialog box, and then apply the
selected font to text on the form.

To display the font dialog box


1.
2.
3.

4.

5.

On the File menu, click New Project.


The New Project dialog box appears.
Click Windows Forms Application and then click OK.
From the Toolbox, drag a Label control to the form, and change the following properties in the
Properties window:

Property

Value

Name

labelFont

Text

Sample text

Add a Button control to the form, and change the following properties in the Properties window:

Property

Value

Name

setFont

Text

Change Font

Drag a FontDialog component from the Dialogs tab of the Toolbox to the form.

fontDialog1 appears in the component tray.


6.
7.

Double-click the button to create the default event handler in the Code Editor.
In the setFont_Click event handler, add the following code to display the font dialog box and
change the font of the text in the label according to the user's choice.

C#

Copy Code

if (fontDialog1.ShowDialog() == DialogResult.OK)
{
this.labelFont.Font = fontDialog1.Font;
}
8.
9.
10.
11.

Press F5 to run the code.


When the form opens, click Change font, click a font in the resulting dialog box, and then click OK.
Verify that the chosen font is applied to the label's text.
Close the application.

How to: Save a File to a Folder


You can use the built-in SaveFileDialog component to enable users to save a file to a folder. To display a
dialog box, you use the ShowDialog method. You can then check whether the user clicked the OK button by
using the DialogResult.OK field.

To display the folder browser dialog box


1.
2.
3.
4.

On the File menu, click New Project.


The New Project dialog box appears.
Click Windows Forms Application and then click OK.
Add a RichTextBox control to the form, leaving the default name, RichTextBox1.
Add a Button control to the form, and change the following properties in the Properties window:

Property

Value

Name

saveTextFile

Text

Save As

5.

Add a SaveFileDialog component to the form.

saveFileDialog1 appears in the component tray.


6.
7.

Double-click the button to add the default event handler in the Code Editor.
In the saveTextFile_Click event handler, add the following code to display the Save As dialog
box. This code saves the text typed in the RichTextBox control to a text file at the specified location.

C#

Copy Code

saveFileDialog1.Filter = "txt files (*.txt)|*.txt";


if(saveFileDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.OK
&& saveFileDialog1.FileName.Length > 0)
{
richTextBox1.SaveFile(saveFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
8.
9.
10.
11.
12.
13.

Press F5 to run the code.


When the form appears, type some text in the rich text box.
Click Save As and then browse to a folder where you want to save the text file.
Specify a name for the text file, and then click OK.
Verify that the text file exists at the specified location.
Close the application

How to: Display an OpenFileDialog Dynamically


You can use the OpenFileDialog component to enable users to browse to a text file and load the selected file
to a RichTextBox control on a Windows Form. This example instantiates OpenFileDialog at run-time.

Example
Copy Code

// Create an OpenFileDialog object.


OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the OpenFileDialog to look for text
files.
openFile1.Filter = "Text Files|*.txt";
// Check if the user selected a file from the
OpenFileDialog.
if(openFile1.ShowDialog() ==
System.Windows.Forms.DialogResult.OK)
9

// Load the contents of the file into a RichTextBox


control.
richTextBox1.LoadFile(openFile1.FileName,
RichTextBoxStreamType.PlainText);
Compiling the Code

Copy the code into the Load_Form1 event handler. When you run the program, you will be
prompted to select a text file. The contents of the selected file will be displayed in a RichTextBox control.

Robust Programming
Use the CheckFileExists, CheckPathExists, DefaultExt, Filter, Multiselect, and ValidateNames properties of the
OpenFileDialog control to limit run-time errors.

How to: Retrieve Data from a Dialog Box


Dialog boxes enable your program to interact with users and retrieve data that users have entered in the
dialog box for use in your application. There are several built-in dialog boxes that you can use in your
applications. For more information, see Using Built-in Dialog Boxes in Your Application. You can also create
your own dialog boxes.
A common task in Windows Forms development is displaying a dialog box to collect information when a user
clicks a button on the main form of an application. You can see an example of this in the Visual C# Express
Edition IDE. When you add a ListBox control to a form, you can click the Items property in the Properties
window to display a dialog box. This dialog box enables you to quickly type text on separate lines of a text
box. The application then adds each line of text to ListBox control when you click OK. If you want to let
users add their own items to a list box in your application, you can create your own string editor dialog box.

To create the main form of your application


1.
2.
3.

4.

On the File menu, click New Project.


The New Project dialog box appears.
Click Windows Forms Application, and then click OK.
A form named Form1 is added to the project.
From the Toolbox, drag a ListBox control to the form, and change the following property in the
Properties window:

Property

Value

Modifiers

Public

Add a Button control to the form, and change the following properties in the Properties window:

Property

Value

Name

addItems

Text

Add

To create a dialog box


1.
2.
3.

On the Project menu, click Add Windows Form, leave the default name Form2, and then click
Add.
From the Toolbox, drag a Label control to the form, and change the Text property to Enter the
String (one per line).
Add a TextBox control to the form, and change the following properties in the Properties window.

Property

Value
10

Multiline

True

Scrollbars

Both

Size

255, 160

4.

Add a Button control to the form, and change the following properties in the Properties window:

Property

Value

Name

okButton

Text

OK

Retrieving Data from a Dialog Box


There are several ways you can pass data from one Windows form to another. In this example, you will pass
Form1 to the constructor of Form2.

To retrieve data from a dialog box.


1.

Double-click the OK button to create the default Click event handler.


Before you add code to this procedure, you should create a variable for the main form and create a new
constructor for the Form2 class.

2.

Add the following code below the default constructor. This code creates an overloaded constructor
that requires Form1 as a parameter.

C#

Copy Code

Form1 mainForm;
public Form2(Form1 mainForm)
{
this.mainForm = mainForm;
InitializeComponent();
}
3.

In the Click event handler of okButton, add the following code. This code clears all existing text in
the list box, assigns each line of text of the text box on Form2 to an array, and then adds each item of
the array to the list box on Form1.

C#

Copy Code

if (this.textBox1.Text != string.Empty)
{
mainForm.listBox1.Items.Clear();
string[] stringsEntered = textBox1.Lines;
for (int count = 0; count < stringsEntered.Length;
count++)
{
11

mainForm.listBox1.Items.Add(stringsEntered[count]);
}
}
this.Close();
4.
5.

Right-click Form1 in Solution Explorer and click View Designer.


Double-click the Add button to add the default Click event handler, and add the following code to
create an instance of Form2 and display the form:

C#

Copy Code

Form2 subForm = new Form2(this);


subForm.Show();
6.
7.
8.

Press F5 to run the code.


When the form opens, click Add.
When the dialog box opens, type the following list of colors, and press ENTER after each word.
Blue
Green
Yellow
Red
9.
Click OK.
10.
Verify that the data typed in the dialog box appears in the list box of Form1.
11.

Close the application.

How to: Add and Clear Items in a ListBox Control


This example adds the contents of a Windows Forms TextBox control to a ListBox control when you click
button1, and clears the contents when you click button2.

Example
Copy Code

private void button1_Click(object sender,


System.EventArgs e)
{
listBox1.Items.Add("Sally");
listBox1.Items.Add("Craig");
}
private void button2_Click(object sender,
System.EventArgs e)
{
listBox1.Items.Clear();
}
12

Compiling the Code


This example requires:

A form with a ListBox control named listBox1 and two buttons named button1 and button2. Add
the button1Click event handler to button1_Click, and the button2Click event handler to
button2_Click.

How to: Determine the Selected Item in a ListBox Control


This example determines which item has been selected in a Windows Forms ListBox control.

Example
Copy Code

private void Form1_Load(object sender, System.EventArgs


e)
{
listBox1.Items.Add("One");
listBox1.Items.Add("Two");
listBox1.Items.Add("Three");
}
private void listBox1_SelectedIndexChanged(object
sender, System.EventArgs e)
{
if ((string)listBox1.SelectedItem == "Two")
MessageBox.Show((string)listBox1.SelectedItem);
}
Compiling the Code
This example requires:

A form named Form1 with a ListBox control named listBox1. Set the Load event handler of Form1
to Form1_Load. Set the SelectedIndexChanged event handler of listBox1 to
listBox1_SelectedIndexChanged.

Note:
This code can also be used with a ComboBox control by
substituting a ComboBox control named comboBox1 for the ListBox
control and changing the code from listBox1 to comboBox1.

How to: Populate a ListBox Control with an Array of Strings


This example adds an array of strings to a ListBox control when the Windows Form opens.

Example
Copy Code

13

private void Form1_Load(object sender, System.EventArgs


e)
{
string [] myList = new string[4];
myList[0]
myList[1]
myList[2]
myList[3]
}

=
=
=
=

"One";
"Two";
"Three";
"Four";

listBox1.Items.AddRange(myList);

Compiling the Code


This example requires:

A form named Form1 with a ListBox control named listBox1. Set the Load event handler of Form1
to Form1_Load.

Note:
This code can also be used with a ComboBox control by
substituting a ComboBox control named comboBox1 for the ListBox
control and changing the code from listBox1 to comboBox1.
Robust Programming
The following conditions may cause an exception:

The array contains one or more null values.

How to: Search for an Item in a ListBox Control


In this example, you add some items to a Windows Forms ListBox control when the form is loaded. Then you
search the ListBox for a specific item by clicking a button on the form. If the item is found, it is selected and
a success message, which contains the item and its index, is sent by using a message box. Otherwise, an
"Item not found" message is sent.

Example
Copy Code

private void Form1_Load(object sender, System.EventArgs


e)
{
listBox1.Items.Add("Angelina");
listBox1.Items.Add("Isabella");
listBox1.Items.Add("Sarah");
}
private void button1_Click(object sender,
System.EventArgs e)
14

// Set the search string:


string myString = "Isabella";
// Search starting from index -1:
int index = listBox1.FindString(myString, -1);
if (index != -1)
{
// Select the found item:
listBox1.SetSelected(index,true);
// Send a success message:
MessageBox.Show("Found the item \"" + myString

"\" at index: " + index);

}
else

MessageBox.Show("Item not found.");

}
Compiling the Code
This example requires:

A form with a ListBox control named listBox1 and a Button control named button1. Set the
button1Click event handler to button1_Click.

Note:
This code can also be used with a ComboBox control by
substituting a ComboBox control named comboBox1 for the
ListBox control and changing the code from listBox1 to
comboBox1.

using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Form2

otherForm =

new Form2();

15

public void GetOtherFormTextBox()


{
if (!otherForm.Visible) otherForm = new Form2();
otherForm.Show();
textBox1.Text = otherForm.textBox2.Text;
}
private void preluc()
{
string s = "Mai suna o data", s1,s2,s3;
s.Replace("suna", "SUNA");
//s=s.Replace("M", "MMMM");
textBox2.Text = s.Replace("suna", "SUNA TARE");
// textBox2.Text = s;;
s1 = s.Substring(3, 4)+ "RRRR";
textBox2.Text = s1;;
s2 = s.Substring(3, 8);
s3 = s2.Length.ToString();
textBox1.Text = s + s1 + s2 + "Length=" +s3;
}
private void button1_Click(object sender, EventArgs e)
{
GetOtherFormTextBox();
}
private void button11_Click(object sender, EventArgs e)
{
otherForm.Close();
}
{

private void button2_Click(object sender, EventArgs e)


textBox1.Text = "Lichidarea informatiei";

}
private void InitForm32_Click(object sender, EventArgs e)
{Form2
ff32 = new Form2();
ff32.button2.Text = "BUTON2";
ff32.button2.Location = new System.Drawing.Point(50, 200);
ff32.button2.ForeColor = System.Drawing.Color.Green;
ff32.button2.Font = new System.Drawing.Font("Microsoft
Sans Serif", 13F);

ff32.Show();
}
private void button3_Click(object sender, EventArgs e)
{
preluc();
}

16

}
}

17

You might also like