我在c#windows窗体中的组合框填充了我数据库中的数据...... 显示成员是字符串,值成员是整数
我现在必须在显示表单之前预先选择它。 我试过了:
combobox.DisplayMember = string;
combobox.Text = string;
combobox.SelectedItem = string;
combobox.SelectedText = string;
combobox.SelectedValue = string;
任何可以给我一点帮助的人? 会非常感兴趣: - )
编辑:ei。也许解决别人的问题...... 请记住,VS2010设计器创建的负载是在构造函数之后加载的。正如我想的那样,不在initializeComponents()中。答案 0 :(得分:3)
如果您的ComboBox是数据绑定的并且您已正确设置DisplayMember和ValueMember属性,那么您只需将SelectedValue属性设置为您要选择的项的值。
例如,如果组合框中有以下对象:
ID Description -- ----------------- 2 Lorem 4 Ipsum 6 Dolor 8 Sit
您可以将DisplayMember设置为“Description”,将ValueMember设置为“ID”。然后,为了选择项目“Dolor”,您只需设置SelectedValue = 6。
答案 1 :(得分:2)
找到Item
,然后将组合框的SelectedItem
属性设置为true。
修改强>
comboBox.SelectedItem = comboBox.Items.Cast<string>().First(o => o == "blala");
如果你的Items是字符串,请使用Cast<string>()
,快速选择combobox.Items会显示该对象。
如果我不记得它是否是winforms,你应该将所选Item的selected属性设置为false,然后将另一个属性设置为true。
检查它,如果是这种情况,只需添加以下行:
combobox.SelectedIndex = -1;
答案 2 :(得分:1)
使用ComboBox.SelectedIndex
。
E.g:
myComboBox.SelectedIndex = [index of item to select];
请注意,ComboBox.Items
是ObjectCollection
,其中有一个名为IndexOf()
的方法。传递给你想要选择的对象的引用,你应该得到适当的索引。
答案 3 :(得分:0)
另一种方式:
combobox.SelectedIndex = combobox.FindStringExact("myString")