Ozzy
Ozzy

Reputation: 10643

C# Listbox set selected item

i have a C# listbox with the values

Profile 1
Profile 2
Profile 3

I want to have Profile 2 selected when the form loads. How do I do this?

Upvotes: 6

Views: 42896

Answers (3)

LEMUEL  ADANE
LEMUEL ADANE

Reputation: 8846

listBox1.Items.Add("Profile 1");

listBox1.Items.Add("Profile 2");

listBox1.Items.Add("Profile 3");

listBox1.SelectedIndex = 1;

Upvotes: 0

Donut
Donut

Reputation: 112895

Set the ListBox.SelectedIndex property in the Form.Shown event.
For example:

public Form1()
{
    InitializeComponent();

    // Adding the event handler in the constructor
    this.Shown += new EventHandler(Form1_Shown);
}    

private void Form1_Shown(object sender, EventArgs e)
{
    myListBox.SelectedIndex = 1;
}

Upvotes: 23

decyclone
decyclone

Reputation: 30840

Put following code in Form.Loaded event:

listBox1.SelectedItem = "Profile 2";

Upvotes: 6

Related Questions