C# comboBox.SelectedItem问题

C# comboBox.SelectedItem问题,c#,winforms,visual-studio-2010,combobox,C#,Winforms,Visual Studio 2010,Combobox,ComboBox正在绑定数据库 string str= comboBox1.SelectedItem.ToString(); 行为str提供System.Data.DataRowView值,但不提供所选项目名称。在分配数据源之前,使用组合框的DisplayMember和ValueMember属性,并使用SelectedValue而不是SelectedItem 例如,如果您有一个列表,其中MyClass有一个属性int ID,另一个字符串标题,并且您希望将其指定为组合框1的数据源,您应该编写:

ComboBox正在绑定数据库

string str= comboBox1.SelectedItem.ToString();

行为
str
提供
System.Data.DataRowView
值,但不提供所选项目名称。

在分配
数据源之前,使用组合框的
DisplayMember
ValueMember
属性,并使用
SelectedValue
而不是
SelectedItem

例如,如果您有一个
列表
,其中
MyClass
有一个属性
int ID
,另一个
字符串标题
,并且您希望将其指定为
组合框1
数据源
,您应该编写:

List<MyClass> myList; 
...

comboBox1.DisplayMember = "Title";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = myList;
列出myList;
...
comboBox1.DisplayMember=“Title”;
comboBox1.ValueMember=“ID”;
comboBox1.DataSource=myList;
现在,
comboBox1.SelectedValue
是一个
对象{int}
,可以将其强制转换为
int
并使用。

ToString()是从对象类继承的。默认实现声明了相应对象的类名

您可能希望将SelectedItem强制转换为DataRowView以访问该行的列值

例:


如果您想要所选项目的文本,只需使用
comboBox1.text

试试这个

if (comboBox1.SelectedItem is DataRowView) {
  string sval = ((DataRowView)comboBox1.SelectedItem).Row["ColumnName"].ToString();
}

这会给出索引,但不会写入内容。如果选择了索引,我说的是selectedValuePrivate void comboBox3_SelectedIndexChanged(object sender,EventArgs e){label2.Text=Combox3.SelectedItem.ToString();}标签会给出{System.Data.DataView}@Maziar sharon似乎想使用组合框的选定项来用文本填充标签。。。问题不在于组合框本身的数据绑定。。。它要么将该标签数据绑定,要么从所选项目中获取所需的文本
if (comboBox1.SelectedItem is DataRowView) {
  string sval = ((DataRowView)comboBox1.SelectedItem).Row["ColumnName"].ToString();
}