[英]comboBox.SelectedItem problem
ComboBox is binding database ComboBox是绑定数据库
string str= comboBox1.SelectedItem.ToString();
the line gives System.Data.DataRowView
value for str
but not giving selected item name.该行给出了str
的System.Data.DataRowView
值,但没有给出所选项目的名称。
try this尝试这个
if (comboBox1.SelectedItem is DataRowView) {
string sval = ((DataRowView)comboBox1.SelectedItem).Row["ColumnName"].ToString();
}
Use the DisplayMember
and ValueMember
Properties for the combobox before you assign the DataSource
, and use SelectedValue
instead of SelectedItem
.在分配DataSource
之前,使用 combobox 的DisplayMember
和ValueMember
属性,并使用SelectedValue
而不是SelectedItem
。
For example, if you have a List<MyClass>
- where MyClass
has a property int ID
, and another one string Title
- and you want to assign it as the DataSource
of comboBox1
, you should write:例如,如果您有一个List<MyClass>
- 其中MyClass
有一个属性int ID
和另一个string Title
-并且您想将其分配为comboBox1
的DataSource
,您应该编写:
List<MyClass> myList;
...
comboBox1.DisplayMember = "Title";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = myList;
Now comboBox1.SelectedValue
is an object{int}
, which can be casted to int
and used.现在comboBox1.SelectedValue
是一个object{int}
,可以转换为int
并使用。
If you want the text of the selected item, just use comboBox1.Text
.如果您想要所选项目的文本,只需使用comboBox1.Text
。
ToString() is inherited from the Object-Class. ToString() 继承自 Object-Class。 The default implementation states the Class Name of the corresponding object.默认实现声明 Class 对应 object 的名称。
you may want to cast the SelectedItem to a DataRowView to access the column-values for that row您可能希望将 SelectedItem 强制转换为 DataRowView 以访问该行的列值
Ex:前任:
String str = ((DataRowView)comboBox1.SelectedItem)["ColumnNameHere"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.