c#
  • sql
  • sql-server
  • winforms
  • 2013-09-22 64 views 1 likes 
    1

    我有這SqlCommandselects項目combo-box取決於從數據庫中得到的是什麼read檢查ComboBox是否包含從SQL中讀取的項目

    組合框包含4個值。 (其中之一應該選擇)

    我有一個問題,因爲我需要檢查從SQL DB讀取的值是否是組合框項目之一。

    請問代碼的外觀應該如何?

    SqlCommand command= new SqlCommand("SELECT * FROM client WHERE ID_K='" + choose_id + "'", con); 
    con.Open(); 
    SqlDataReader read= command.ExecuteReader(); 
    
    if (read.Read()) 
    { 
        if (read["price"] != DBNull.Value) 
        { 
         cb_choose_price.SelectedItem = read.GetString(read.GetOrdinal("price")); 
        }} con.Close(); 
    
    +0

    你能你的成員的名字翻譯成英文時,你問的講英語的網站上?這將有助於他人理解你的代碼。 –

    回答

    2

    ComboBox組件的SelectedItem屬性綁定到存儲在它(或更確切地說引用這些對象)的實際的對象。如果您想通過顯示的字符串設置選定的項目,則必須獲取項目集合,將其轉換爲字符串,然後選擇適當的項目。查看我的Person類型的代碼示例。

    當您將組合框綁定到數據源時,它會使用ToString()方法顯示引用的對象。例如:

    class Person 
    { 
        public string Name { get; set; } 
        public int Age { get; set; } 
    } 
    
    var persons = new List<Person> { 
        new Person("Adam", 10), 
        new Person("Thomas", 20) }; 
    comboBox.DataSource = persons; 
    comboBox.DisplayMember = "Name"; 
    
    comboBox.SelectedItem = "Adam"; // this will not display a person named Thomas because the combobox is binded to the Person type 
    comboBox.SelectedItem = persons.Where(p => p.Name == "Thomas").Single(); // this will show Adam if it is available in the comboBox 
    

    更新基於註釋:

    我想我明白了這一切,但有什麼辦法來檢查是否應該選擇(從字符串的項目 SQL DB)甚至存在於組合框中的 項目列表中?

    var item = comboBox1.Items.Cast<Person>(); 
    bool isThereAdam = item.Any(i => i.Name == "Adam"); 
    
    +0

    感謝您的回答和您的時間。我想我理解了所有這些,但是有什麼方法可以檢查應該選擇的項目(來自SQL DB的字符串)是否存在於組合框的項目列表中? – Marek

    +0

    當然。我會更新我的答案。 –

    +0

    難道你不這樣認爲:''cb_vyber_cena.Items.Contains(precti.GetString(precti.GetOrdinal(「price」)))'可能解決這個問題嗎? – Marek

    0

    如果你正在做數據使用一個DataTable綁定,這應該工作:

    private void BindClientCombobox(DataTable clientDataTable) 
    { 
        this.cbClients.DataSource = clientDataTable; 
        this.cbClients.ValueMember = "client_id"; 
        this.cbClients.DisplayMember = "client_name"; 
    } 
    
    private bool ContainsClientID(int clientID) 
    { 
        return this.cbClients.Items.Cast<DataRowView>().Any(drv => (int)drv.Row.ItemArray[0] == clientID); 
    } 
    
    private bool ContainsClientName(string clientName) 
    { 
        return this.cbClients.Items.Cast<DataRowView>().Any(drv => (string)drv.Row.ItemArray[1] == clientName); 
    } 
    
    相關問題