Export (0) Print
Expand All
Expand Minimize

Code: Adding Items to a ListBox Control (Visual C#)

Visual Studio .NET 2003

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.

See Also

Windows Forms Example Topics

Show:
© 2014 Microsoft