組合框被結合數據庫comboBox.SelectedItem問題
string str= comboBox1.SelectedItem.ToString();
行給出了str
System.Data.DataRowView
價值,但不給選定的項目名稱。
組合框被結合數據庫comboBox.SelectedItem問題
string str= comboBox1.SelectedItem.ToString();
行給出了str
System.Data.DataRowView
價值,但不給選定的項目名稱。
使用的組合框的DisplayMember
和ValueMember
屬性分配前DataSource
,並使用SelectedValue
代替SelectedItem
。
舉例來說,如果你有一個List<MyClass>
- 在MyClass
有一個屬性int ID
,另一個string Title
- 你希望把它分配爲comboBox1
的DataSource
,你應該寫:
List<MyClass> myList;
...
comboBox1.DisplayMember = "Title";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = myList;
現在comboBox1.SelectedValue
是object{int}
,可以鑄造到int
並使用。
ToString()從對象類繼承。默認實現指定相應對象的類名稱。
可能要到的SelectedItem轉換爲DataRowView的訪問列值,該行
例:
String str = ((DataRowView)comboBox1.SelectedItem)["ColumnNameHere"];
如果你想選擇的項目的文本,只要使用comboBox1.Text
。
試試這個
if (comboBox1.SelectedItem is DataRowView) {
string sval = ((DataRowView)comboBox1.SelectedItem).Row["ColumnName"].ToString();
}
這給指數而不是內容寫入 – sharon 2011-06-01 23:23:21
,一個是SelectedIndex的,我說的是選擇的值 – 2011-06-01 23:25:58
私人無效comboBox3_SelectedIndexChanged(對象發件人,EventArgs的) { LABEL2 .Text = comboBox3.SelectedItem.ToString(); } – sharon 2011-06-01 23:27:12