2011-06-01 23 views
2

組合框被結合數據庫comboBox.SelectedItem問題

string str= comboBox1.SelectedItem.ToString(); 

行給出了strSystem.Data.DataRowView價值,但不給選定的項目名稱。

回答

2

使用的組合框的DisplayMemberValueMember屬性分配前DataSource,並使用SelectedValue代替SelectedItem

舉例來說,如果你有一個List<MyClass> - 在MyClass有一個屬性int ID,另一個string Title - 你希望把它分配爲comboBox1DataSource,你應該寫:

List<MyClass> myList; 
... 

comboBox1.DisplayMember = "Title"; 
comboBox1.ValueMember = "ID"; 
comboBox1.DataSource = myList; 

現在comboBox1.SelectedValueobject{int},可以鑄造到int並使用。

+1

這給指數而不是內容寫入 – sharon 2011-06-01 23:23:21

+0

,一個是SelectedIndex的,我說的是選擇的值 – 2011-06-01 23:25:58

+0

私人無效comboBox3_SelectedIndexChanged(對象發件人,EventArgs的) { LABEL2 .Text = comboBox3.SelectedItem.ToString(); } – sharon 2011-06-01 23:27:12

1

ToString()從對象類繼承。默認實現指定相應對象的類名稱。

可能要到的SelectedItem轉換爲DataRowView的訪問列值,該行

例:

String str = ((DataRowView)comboBox1.SelectedItem)["ColumnNameHere"]; 
2

如果你想選擇的項目的文本,只要使用comboBox1.Text

4

試試這個

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