2011-07-18 32 views
5

我有一個組合框,我填充了這樣的數據:如何獲得組合框C#

DataTable dt = new DataTable(); 

using (SQLiteConnection conn = connection.Conn) 
{    
    using (SQLiteCommand cmd = new SQLiteCommand(conn)) 
    { 
     cmd.CommandText = "select id, description from category"; 
     conn.Open(); 

     using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd)) 
     { 
      da.Fill(dtChargeCodes); 
      comboBox1.DataSource = dt; 
      comboBox1.DisplayMember = "description"; 
      comboBox1.ValueMember = "id"; 
     }          
    }    
} 

我試圖才達到是讓ComboBox中所選項目的數據,當我試圖使用MessageBox.Show(comboBox1.SelectedItem.ToString());來顯示它時,我得到的是類型System.Data.DataRowView.而不是表類別中字段描述的實際值。請幫助...謝謝。

回答

5

要麼使用

comboBox1.SelectedText 

((System.Data.DataRowView)(comboBox1.SelectedItem))["description"] 

您可能需要,如果你需要訪問SelectedIndexChanged事件的價值,使用第二種方法(見here

2

我想你需要

MessageBox.Show(comboBox1.SelectedItem.Value.ToString()) 
+0

我覺得有沒有'ComboBox.Selected'的'Value'屬性。 – yonan2236

+0

問題是,我認爲你得到這個項目。項目上應該有一些屬性可以給你價值。對不起 - 我無法訪問檢查ATM的環境。 –

5

試試這個:

MessageBox.Show(comboBox1.SelectedValue); 
+0

這將顯示查詢中的「id」值「select id,description from category」。不是說明.... – yonan2236

+0

對不起,沒有正確閱讀這個問題。通常這個價值就是你所追求的。 –

+0

還有其他方法嗎? – yonan2236

1

一些解釋:

MessageBox.Show(comboBox1.SelectedValue.ToString()); //get selected item value 
MessageBox.Show(comboBox1.Text); //get selected item text 
2

如果你正在尋找的屏幕值使用此:

MessageBox.Show(combobox1.SelectedText); 
+0

注意:如果DropDownStyle設置爲DropDownList,返回值是一個空字符串(「」)。 – Reniuz

+0

還有其他方法嗎? – yonan2236