I have a UserControl in a Form that contains a Listbox. I would like to automatically select the first item in the Listbox (assuming there is at least one item) but I cannot get the following code to work:
private void Lightnings_Mode_Load(object sender, EventArgs e)
{
this.Size = new Size(416, 506);
this.Location = new Point(23, 258);
listBoxIndexs();
listBoxControl1.MyListBox.SelectedIndex = 0;
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
listBoxControl1.MyListBox.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
this.listBoxControl1.ItemRemoved += new EventHandler<ItemEventArgs>(listBoxControl1_ItemRemoved);
}
This line: listBoxControl1.MyListBox.SelectedIndex = 0; will mark the first ListBox item in blue like it is selected. But it’s not realy selecting the item!
So I tried to add this:
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
But it’s not working either.
This is the SelectedIndex event:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
item = listBoxControl1.MyListBox.SelectedItem.ToString();
this.f1.PlayLightnings();
f1.pdftoolsmenu();
int indx = listBoxControl1.MyListBox.SelectedIndex;
if (listBoxControl1.Indices.Contains(indx))
{
if (item != null && !pdf1.Lightnings.Contains(item.ToString()))
{
pdf1.Lightnings.Add(item.ToString());
}
}
}
The name of the event is not right I have to change it since it’s the ListBox over the UserControl but it’s the right one.
When I put a breakpoint in the SelectedIndex event and I click on an item, it stops at the breakpoint. But I want it to go to the selectedIndex event automatically once I show/open the new Form with the UserControl and the ListBox.
So if I put a breakpoint in the SelectedIndex event, when I click the button in Form1 to show/open the new Form it will automatically stop in the breakpoint like I was clicking the first item.
This is in Form1 the code that show the new Form:
if (toolStripComboBox2.SelectedIndex == -1 && toolStripComboBox1.SelectedIndex == -1)
{
}
else
{
Lightnings_Extractor.Lightnings_Mode lightningsmode1 = new Lightnings_Extractor.Lightnings_Mode(this);
lightningsmode1.Show();
}
Everything is working except for selecting the first item automatically.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.setselected(v=vs.90).aspx
instead of
Try this: