我在包含列表框的窗体中有一个 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 部分中的任何设置来帮助避免这种事情。
关于c# - 如何使 ListBox 中的第一项自动被选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14295326/