C# comboBox.SelectedItem问题
ComboBox正在绑定数据库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的数据源,您应该编写:
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();
}