简体   繁体   English

comboBox.SelectedItem 问题

[英]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.该行给出了strSystem.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 的DisplayMemberValueMember属性,并使用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 -并且您想将其分配为comboBox1DataSource ,您应该编写:

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.

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