要解决“运行时,C# listbox selected index stays at -1 when run”的问题,可以尝试以下解决方法:
- 确保在设置ListBox的数据源之前,将ListBox的SelectionMode属性设置为Single或Extended。
listBox1.SelectionMode = SelectionMode.Single;
- 确保在设置ListBox的数据源之前,将ListBox的SelectedIndexChanged事件处理程序与ListBox关联起来。
listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
- 在ListBox的数据源更改后,确保ListBox的SelectedIndex属性被正确设置。
listBox1.DataSource = yourDataSource;
listBox1.SelectedIndex = 0; // 或者设置为合适的索引值
- 确保ListBox的数据源中包含的对象具有适当的ToString()方法重写。如果没有正确重写ToString()方法,ListBox将无法正确显示对象。
public override string ToString()
{
return yourProperty.ToString(); // 替换为适当的属性
}
- 确保在ListBox的SelectedIndexChanged事件处理程序中使用SelectedIndex属性来获取选定项的索引。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = listBox1.SelectedIndex;
// 执行适当的操作
}
希望这些解决方法能够帮助您解决问题。如果问题仍然存在,请提供更多的代码示例以便我们更好地帮助您。