[英]How do I make that the first item in ListBox will be selected automatically?
我在包含列表框的窗体中有一个UserControl。 我想自动选择列表框中的第一个项目(假设至少有一个项目),但是我无法使以下代码正常工作:
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);
}
这行:listBoxControl1.MyListBox.SelectedIndex = 0; 会像选中它一样将第一个ListBox项目标记为蓝色。 但这并不是真的选择项目!
因此,我尝试添加以下内容:
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
但这也不起作用。
这是SelectedIndex事件:
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());
}
}
}
事件的名称不正确,我必须更改它,因为它是UserControl上的ListBox,但它是正确的。
当我在SelectedIndex事件中放置一个断点并单击一个项目时,它会在该断点处停止。 但是,我希望使用UserControl和ListBox显示/打开新窗体后,它会自动进入selectedIndex事件。
因此,如果我在SelectedIndex事件中放置一个断点,则当我单击Form1中的按钮以显示/打开新窗体时,它会自动在断点处停止,就像我单击第一项一样。
这是Form1中显示新表单的代码:
if (toolStripComboBox2.SelectedIndex == -1 && toolStripComboBox1.SelectedIndex == -1)
{
}
else
{
Lightnings_Extractor.Lightnings_Mode lightningsmode1 = new Lightnings_Extractor.Lightnings_Mode(this);
lightningsmode1.Show();
}
一切正常,除了自动选择第一个项目。
您可能需要在开始收听事件以及实际广播事件的地方交换线路。
尝试更改:
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
listBoxControl1.MyListBox.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
对此:
listBoxControl1.MyListBox.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
通常,我在表单的OnLoad部分中订阅EventHandlers,并调整OnShow部分中的任何设置来帮助避免这种情况。
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.setselected(v=vs.90).aspx
代替
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SelectedIndex = 0;
尝试这个:
if (this.listBoxControl1.MyListBox.Items.Count > 0)
this.listBoxControl1.MyListBox.SetSelected(0,true);
您必须更改项目本身的属性:
listBoxControl1.Focus();
listBoxControl1.Items[0].Selected = true;
第一行不是真正必要的,但我将其包括在内以防止出现某些问题。 如果列表框中没有任何项目,则还应该处理IndexOutOfRangeException
。
您可以简单地尝试:使用0索引。
listBoxControl1.Items[0].Selected = true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.