[英]How to set default selected item of listbox in winform c#?
I try to set like this: 我尝试这样设置:
ListBox lb = new ListBox();
/* Bind datas */
lb.SelectedItem = someObject;
lb truely selected the someObject item. lb确实选择了someObject项目。 But it would select the 1st item at first.
但是它将首先选择第一项。 And that motion cause SelectedIndexChanged event which I don't wanted.
那个动作导致了我不想要的SelectedIndexChanged事件。
I just want SelectedIndexChanged be called when someObject selected. 我只希望在选择someObject时调用SelectedIndexChanged。 How could I do to fix this?
我该如何解决?
Use a flag on the form/control to disable the event when you don't want it to fire. 当您不希望触发该事件时,请在窗体/控件上使用一个标志来禁用该事件。
public class Form1 : Form
{
private bool itemsLoading;
public Form1()
{
InitializeComponent();
LoadListItems();
}
private void LoadListItems()
{
itemsLoading = true;
try
{
listBox1.DataSource = ...
listBox1.SelectedItem = ...
}
finally
{
itemsLoading = false;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (itemsLoading)
return;
// Handle the changed event here...
}
}
don't add the selectedIndexChanged event until after you have changed the selectedItem to someObject ? 在将selectedItem更改为someObject之后,是否才添加selectedIndexChanged事件?
remove the event out of the form editor, or the designer.cs, and add it yourself manually by using the same code it auto generates? 从表单编辑器或designer.cs中删除事件,然后使用它自动生成的相同代码手动添加它?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.