Share via


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

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 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.

See Also

Concepts

Designing a User Interface in Visual C#

Other Resources

ListBox and ComboBox Controls

Visual C# Guided Tour