简体   繁体   English

C#在组合框中选择一个值

[英]c# select a value in combobox

My combobox in c# windows forms is filled with data from my database... Display Members are strings, value members are ints 我在C#Windows窗体中的组合框充满了数据库中的数据...显示成员是字符串,值成员是整数

I now have to preselect it before showing the form. 现在,在显示表单之前,我必须预先选择它。 I have tried: 我努力了:

combobox.DisplayMember = string;
combobox.Text = string;
combobox.SelectedItem = string;
combobox.SelectedText = string;
combobox.SelectedValue = string;

Anyone that can give me a little help? 任何可以给我一点帮助的人吗? Would be much appriciated :-) 会被应用很多:-)

EDIT : ei. 编辑:ei。 maybe solution for others... Remember that the load created by VS2010 designer is loaded after constructor. 也许是其他人的解决方案...请记住,由VS2010设计器创建的加载是在构造函数之后加载的。 not within initializeComponents(), as I thought. 如我所想,不在initializeComponents()中。

If your ComboBox is data-bound and you have properly set up the DisplayMember and ValueMember properties, then you can simply set the SelectedValue property to the value of the item you want to select. 如果您的ComboBox是数据绑定的,并且已经正确设置了DisplayMember和ValueMember属性,则只需将SelectedValue属性设置为要选择的项目的值即可。

For example, if you had the following objects in your combo box: 例如,如果您的组合框中有以下对象:

ID  Description
--  -----------------
2   Lorem
4   Ipsum
6   Dolor
8   Sit

You would set the DisplayMember to "Description" and ValueMember to "ID". 您可以将DisplayMember设置为“ Description”,将ValueMember设置为“ ID”。 Then in order to select the item "Dolor", you would just set SelectedValue = 6. 然后,为了选择项目“ Dolor”,只需将SelectedValue设置为6。

Find the Item then set the SelectedItem property of combobox to true. 找到该Item然后将组合框的SelectedItem属性设置为true。

EDIT: 编辑:

comboBox.SelectedItem = comboBox.Items.Cast<string>().First(o => o == "blala");

use the Cast<string>() if your Items is string, Quick Qatching the combobox.Items will show you the object. 如果您的Items是字符串,请使用Cast<string>() ,快速组合框。Items将向您显示对象。

In a case that I can't remember exactly whether it was winforms or not, you should set the selected Item's selected property to false, then set another one to true. 如果我无法确切记住它是否是winforms,则应将selected Item的selected属性设置为false,然后将另一个属性设置为true。

check it and if that's the case just add this line: 检查它,如果是这种情况,只需添加以下行:

combobox.SelectedIndex = -1;

Use ComboBox.SelectedIndex . 使用ComboBox.SelectedIndex

Eg: 例如:

myComboBox.SelectedIndex = [index of item to select];

Note that ComboBox.Items is an ObjectCollection , which has a method called IndexOf() . 请注意, ComboBox.Items是一个ObjectCollection ,它具有一个称为IndexOf()的方法。 Pass it a reference to the object you want to select, and you should get the proper index back. 将其传递给您要选择的对象的引用,然后应该返回正确的索引。

其他方式:

combobox.SelectedIndex = combobox.FindStringExact("myString")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM