Code: Determining Which Control on a Form is Selected
This example displays the name of the currently selected Windows Forms control in a Label control.
Example
private void DisplayNameOfActiveControl()
{
label1.Text = this.ActiveControl.Name;
}
Compiling the Code
This example requires:
- A form with a Label control named label1
Code: Adding Items to a ListBox Control
This example adds the contents of a Windows Forms TextBox control to a ListBox control when the TextBox control loses focus.
Example
private void textBox_Leave(object sender, System.EventArgs e)
{
listBox1.Items.Add(((TextBox)sender).Text);
}
Compiling the Code
This example requires:
- A form with a ListBox control named listBox1 and three TextBox controls named textBox1, textBox2, and textBox3. Set each TextBox’s Leave event handler to textBox_Leave.
Note This 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
To avoid duplicate entries in the list, you should search for a match before adding the contents of the TextBox to the list. For an example, see Code: Searching for an Item in a ListBox Control
Code: Searching for an Item in a ListBox Control
This example searches for a string in a Windows Forms ListBox control.
Example
private void button1_Click(object sender, System.EventArgs e)
{
listBox1.Items.Add(“One”);
listBox1.Items.Add(“Two”);
listBox1.Items.Add(“Three”);
if (listBox1.FindString(“Two”) != -1)
MessageBox.Show(“Found it!”);
}
Code: Selecting an Item in a ListBox Control
This example selects and highlights an item in a Windows Forms ListBox control.
Example
private void button1_Click(object sender, System.EventArgs e)
{
listBox1.Items.Add(“One”);
listBox1.Items.Add(“Two”);
listBox1.Items.Add(“Three”);
listBox1.SelectedIndex = listBox1.FindString(“Two”);
}
Compiling the Code
This example requires:
- A form with a ListBox control named listBox1 and a Button control named button1. Set button1’s Click event handler to button1_Click.
Note This 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.
Compiling the Code
This example requires:
- A form with a ListBox control named listBox1 and a Button control named button1. Set button1’s Click event handler to button1_Click.
Note This 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.
Code: Determining the Selected Item in a ListBox Control
This example determines which item has been selected in a Windows Forms ListBox control.
Example
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 Form1’s Load event handler to Form1_Load. Set listBox1’s SelectedIndexChanged event handler to listBox1_SelectedIndexChanged.
Note This 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.
Code: Populating a ListBox Control with an Array of Strings
This example adds an array of strings to a Windows Forms ListBox control.
Example
private void Form1_Load(object sender, System.EventArgs e)
{
string [] myList = new string[4];
myList[0] = “One”;
myList[1] = “Two”;
myList[2] = “Three”;
myList[3] = “Four”;
listBox1.Items.AddRange(myList);
}
Compiling the Code
This example requires:
- A form named Form1 with a ListBox control named listBox1. Set Form1’s Load event handler to Form1_Load.
Note This 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.
Code: Converting the Text in a TextBox Control to an Integer
This example demonstrates two methods of converting text data to integer data.
Example
int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);
Code: Determining the Selected Text in a TextBox Control
This example programmatically selects text in a Windows Forms TextBox control and retrieves the selected text.
Example
private void button1_Click(object sender, System.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 button1’s Click event handler to button1_Click.
Note This 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.
Code: Formatting Characters in Bold in a RichTextBox Control
This example adds the text “This text is in bold.” to an existing RichTextBox control.
Example
richTextBox1.Rtf = @”{\rtf1\ansi This is in \b bold\b0.}”;
Compiling the Code
This example requires:
- A RichTextBox control named richTextBox1.
Code: Creating a Context Menu and Attaching it to a Control
This example programmatically creates a Windows Forms context menu and associates it with a control.
Example
private void Form1_Load(object sender, System.EventArgs e)
{
System.Windows.Forms.ContextMenu contextMenu1;
contextMenu1 = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem menuItem1;
menuItem1 = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem2;
menuItem2 = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem menuItem3;
menuItem3 = new System.Windows.Forms.MenuItem();
contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {menuItem1, menuItem2, menuItem3});
menuItem1.Index = 0;
menuItem1.Text = “MenuItem1”;
menuItem2.Index = 1;
menuItem2.Text = “MenuItem2”;
menuItem3.Index = 2;
menuItem3.Text = “MenuItem3”;
textBox1.ContextMenu = contextMenu1;
}
Compiling the Code
This example requires:
- A Windows Form named Form1 and a TextBox control named textBox1. Set Form1’s Load event handler to Form1_Load
Code: Creating a Group of Radio Buttons from a String Array
This example programmatically creates a group of Windows Forms radio buttons and set their Text properties to values from an array of strings.
Example
private void button1_Click(object sender, System.EventArgs e)
{
string [] stringArray = new string[3];
stringArray[0] = “Yes”;
stringArray[1] = “No”;
stringArray[2] = “Maybe”;
System.Windows.Forms.RadioButton [] radioButtons = new System.Windows.Forms.RadioButton[3];
for(int i=0; i<3; ++i)
{
radioButtons[i] = new RadioButton();
radioButtons[i].Text = StringArray[i];
radioButtons[i].Location = new System.Drawing.Point(10, 10+i*20);
this.Controls.Add(radioButtons[i]);
}
}
Compiling the Code
This example requires:
- A Windows Form with a Button control named button1. Set button1’s Click event handler to button1_Click.
Code: Creating a ToolTip for a Control
This example programmatically creates a ToolTip for a Windows Forms control.
Example
private void Form1_Load(object sender, System.EventArgs e)
{
System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip(this.textBox1, “Hello”);
}
Compiling the Code
This example requires:
- A form named Form1 with a TextBox control named textBox1. Set Form1’s Load event handler to Form1_Load.
Code: Adding a Node to the Selected Node of a TreeView Control
This example adds one node to the selected node of an existing TreeView control.
Example
TreeNode node = treeView1.SelectedNode;
node.Nodes.Add(“New node below selected node”);
Code: Adding Nested Nodes to a TreeView Control
This example adds a first-level node and a second-level node to an existing TreeView control.
Example
TreeNode node = treeView1.Nodes.Add(“Level one node”);
node.Nodes.Add(“Level two node”);
Code: Determining the Selected Node in a TreeView Control
This example sets a reference to the selected node of existing TreeView control.
TreeNode node = treeView1.SelectedNode;
Compiling the Code
This example requires:
- A TreeView control named treeView1.
Code: Adding Nodes to a TreeView Control
This example adds three first-level nodes to an existing TreeView control.
Example
treeView1.Nodes.Add(“First Node”);
treeView1.Nodes.Add(“Second Node”);
treeView1.Nodes.Add(“Third Node”);
Code: Databinding a DataTable of String Values to a Windows DataGrid Control
This example creates a data table with two columns and two rows and then binds it to an existing DataGrid control.
Example
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn(“Item”, typeof(string)));
dt.Columns.Add(new DataColumn(“Color”, typeof(string)));
dt.Rows.Add(new string[] {“table”, “brown”});
dt.Rows.Add(new string[] {“chair”, “white”});
dataGrid1.DataSource = dt;
Compiling the Code
This example requires:
- A DataGrid control named dataGrid1.
Code: Databinding an Array of String Values to a Windows ListBox Control
This example adds three strings to an existing ListBox control.
Example
listBox1.DataSource = new string[] { “one”, “two”, “three” };
Compiling the Code
This example requires:
- A ListBox control named listBox1.
Code: Determining the Selected Cell in a Windows DataGrid Control
This example sets a reference to the selected cell of an existing DataGrid control.
System.Windows.Forms.DataGridCell selectedCell = dataGrid1.CurrentCell;
Code: Displaying a Web Page from a LinkLabel Control
This example displays a Web page in the default browser when a user clicks a Windows Forms LinkLabel control.
Example
private void Form1_Load(object sender, System.EventArgs e)
{
linkLabel1.Text = “Click here to get more info.”;
linkLabel1.Links.Add(6, 4, “www.microsoft.com”);
}
private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(e.Link.LinkData.ToString());
}
Compiling the Code
This example requires:
- A form named Form1 with a LinkLabel control named linkLabel1.
- An active Internet connection.
Code: Displaying an OpenFileDialog Dynamically
This example instantiates and displays an OpenFileDialog control.
Example
OpenFileDialog openFile = new OpenFileDialog();
openFile.DefaultExt = “doc”;
// The Filter property requires a search string after the pipe ( | )
openFile.Filter = “Word documents (*.doc)|*.doc”;
openFile.ShowDialog();
if( openFile.FileNames.Length > 0 )
{
foreach( string filename in openFile.FileNames )
{
// Insert code here to process the files.
}
}
Robust Programming
You can use the FileOK event of the OpenFileDialog control to be certain that the user selected a file and clicked the OK button on the dialog box.
Use the CheckFileExists, CheckPathExists, DefaultExtension, Filter, Multiselect, and ValidateNames properties of the OpenFileDialog control to limit run-time errors.
Code: Displaying One Form from Another
This example displays a second form from another Windows Form.
Example
private void button1_Click(object sender, System.EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
}
Compiling the Code
This example requires:
- Two Windows Forms named Form1 and Form2. Form1 contains a Button control named button1. Set button1’s Click event handler to button1_Click.
Code: Displaying the Time in a StatusBar Control
This example displays the current time in hh:mm format in a StatusBar control.
Example
private void timer1_Tick(object sender, System.EventArgs e)
{
statusBar1.Panels[0].Text = DateTime.Now.ToShortTimeString();
}
Compiling the Code
The form must contain a Timer control with Enabled set to True, and a StatusBar with a Panel added to the Panels property and the ShowPanels property set to True.
The code is part of the event handler for the Timer control’s Tick event, as shown.
Robust Programming
The following conditions may cause an exception:
Code: Drawing Graphics on a Windows Form
This example draws a circle and a square on a form.
Example
System.Drawing.Graphics graphics = this.CreateGraphics();
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);
graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
Compiling the Code
This code is to be added to a class that derives from System.Windows.Forms.Form. The this refers to the instance of the form
Code: Getting a Value from Another Form
This example retrieves a value from a text box on a Windows Form and displays it in a text box on another form.
Example
In Form1.cs:
private Form2 otherForm;
private void GetOtherFormTextBox()
{
textBox1.Text = otherForm.TextBox1.Text;
}
In Form2.cs:
public TextBox TextBox1
{
get
{
return textBox1;
}
}
Compiling the Code
This example requires:
- Two forms named Form1 and Form2, each containing a TextBox control named textBox1. Form1 should create an instance of Form2 and assign it to otherForm; GetOtherFormTextBox will the text in Form2’s textBox1 to Form1’s textBox1
Code: Hiding a DataColumn in a DataGrid Where the DataSource is a DataTable
This example hides the “X” column of a DataTable object that is displayed in an existing Windows Forms DataGrid control.
Example
private void HideColumnOfDataSet()
{
System.Data.DataTable points = new System.Data.DataTable(“Points”);
points.Columns.Add(new DataColumn(“X”, typeof(int)));
points.Columns.Add(new DataColumn(“Y”, typeof(int)));
points.Rows.Add(new object[]{1, 2});
points.Rows.Add(new object[]{3, 5});
dataGrid1.DataSource = points;
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = “Points”;
dataGrid1.TableStyles.Add(tableStyle);
dataGrid1.TableStyles[“Points”].GridColumnStyles[“X”].Width = 0;
}
Compiling the Code
This example requires:
- A Windows Form with a DataGrid control named dataGrid1.
If the data source is a DataSet object, set the DataMember property of the DataGrid to the table’s name.
DataTable and DataColumn objects in typed datasets also have string-typed names. To find the name of the table, example the table’s Name property. To find the name of the DataColumn, examine the column’s Name property.
Robust Programming
The following conditions may cause an exception:
- The MappingName property does not match the name of the DataTable (NullReferenceException Class).
- Retrieving an item from the GridColumnStyles collection before the TableStyle is added to the DataGrid.TableStyles collection. The GridColumnStyles collection is filled when the TableStyle object is added to the TableStyles collection (NullReferenceException Class).
- A TableStyle added to the DataGrid.TableStyles collection does not have a unique MappingName (ArgumentException Class).
- The DataSource property of the DataGrid is not set before accessing the GridColumnStyles collection (NullReferenceException Class).
Code: Hiding a DataColumn in a DataGrid Where the DataSource is an Array
This example hides the “X” column of a DataGrid that uses an array of Point objects as the data source.
Example
private void HideColumnOfArray()
{
System.Drawing.Point [] points = { new Point(1, 2), new Point(3, 5), new Point(5, 6)};
dataGrid1.DataSource = points;
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = “Point[]”;
dataGrid1.TableStyles.Add(tableStyle);
dataGrid1.TableStyles[“Point[]”].GridColumnStyles[“X”].Width = 0;
}
Compiling the Code
This example requires:
- A Windows Form with a DataGrid control named dataGrid1.
The MappingName, a string, is the type of the array with “[]” appended. Thus, if the data source is an array of Point objects, the mapping name is “Point[]”.
Robust Programming
The following conditions may cause an exception:
- The MappingName property is not property formatted (NullReferenceException Class).
- Retrieving an item from the GridColumnStyles collection before the TableStyle is added to the DataGrid.TableStyles collection. The GridColumnStyles collection is filled when the TableStyle object is added to the TableStyles collection (NullReferenceException Class).
- A TableStyle added to the DataGrid.TableStyles collection does not have a unique MappingName (ArgumentException Class).
- The DataSource property of the DataGrid is not set before accessing the GridColumnStyles collection (NullReferenceException Class).
Code: Hiding a DataColumn in a DataGrid Where the DataSource is an ArrayList
This example hides one column of a DataGrid that uses an ArrayList of Point objects as a data source.
Example
private void HideColumnOfArrayList()
{
System.Collections.ArrayList list = new System.Collections.ArrayList();
list.AddRange( new Point[]{ new Point(1, 2), new Point(3, 5), new Point(5, 6) } );
dataGrid1.DataSource = list;
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = “ArrayList”;
dataGrid1.TableStyles.Add(tableStyle);
object o = dataGrid1.TableStyles[“ArrayList”];
dataGrid1.TableStyles[“ArrayList”].GridColumnStyles[“X”].Width = 0;
}
Compiling the Code
This example requires:
- A Windows Form with a DataGrid control named dataGrid1.
When the data source is an ArrayList object, the MappingName is “ArrayList”.
Robust Programming
The following conditions may cause an exception:
- The MappingName property is not “ArrayList”(NullReferenceException Class).
- Retrieving an item from the GridColumnStyles collection before the TableStyle is added to the DataGrid.TableStyles collection. The GridColumnStyles collection is filled when the TableStyle object is added to the TableStyles collection (NullReferenceException Class).
- A TableStyle added to the DataGrid.TableStyles collection does not have a unique MappingName (ArgumentException Class).
- All the objects in the ArrayList are not of the same type of the first item or a derived type of the first item (TargetInvocationException Class).
- The DataSource property of the DataGrid is not set before accessing the GridColumnStyles collection (NullReferenceException Class).
Code: Retrieving an Image that is an Embedded Resource
This example retrieves an image that is an embedded resource of the assembly.
Example
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream(“AssemblyName.ImageFile.jpg”);
this.pictureBox1.Image = Image.FromStream(file);
Compiling the Code
This example requires:
- A Windows Form with a PictureBox control named pictureBox1.
Add the image file to the project, and set the Build Action property to Embedded Resource in Solution Explorer.
Replace “AssemblyName.ImageFile.jpg” with the name of the resource, as it is known in the assembly. Use the GetManifestResourceNames method of the Assembly object to find the resource name. See Code: Finding the Names of Resources in an Assembly.
Robust Programming
The following conditions may cause an exception:
- The embedded resource does not exist in the assembly, and the call to GetManifestResourceStream returns Nothing.
- There may not be an application associated with the file type (the file extension).
Code: Retrieving the Data from the Selected Cell in a Windows DataGrid Control
This example retrieves the selected data in an existing DataGrid control filled with integer values.
Example
System.Windows.Forms.DataGridCell selectedCell = dataGrid1.CurrentCell;
object selectedItem = dataGrid1[selectedCell.RowNumber, selectedCell.ColumnNumber];
int cellValue = Convert.ToInt32(selectedItem);
Compiling the Code
This example requires:
- A DataGrid control named dataGrid1.
Robust Programming
If the DataGrid is not bound to a data source, or if no cell is selected, then the selected cell is the cell in row 0 and column 0.
The following conditions may cause an exception:
Code: Selecting a Range of Dates in a Calendar Control
This example selects a range of dates in a Windows Forms MonthCalendar control. In this example, when the user selects a date the week is selected.
Example
private void monthCalendar1_DateSelected(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
DateTime startDate = e.Start;
startDate = startDate.AddDays(-(double)startDate.DayOfWeek);
monthCalendar1.SelectionStart = startDate;
monthCalendar1.SelectionEnd = startDate.AddDays(6);
}
Compiling the Code
This example requires:
- A Windows Form with a MonthCalendar control named monthCalendar1. Set monthCalendar1’s DateSelected event handler to monthCalendar1_DateSelected.
Code: Changing the Background Color of a Form
This example changes the background color of a Windows Form programmatically.
Example
private void Form1_Click(object sender, System.EventArgs e)
{
this.BackColor = System.Drawing.Color.DarkBlue;
}
Compiling the Code
This example requires:
- A form named Form1. Set Form1’s Click event handler to Form1_Click.