c#
  • sql
  • sql-server
  • winforms
  • 2013-09-22 57 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); 
    } 
    
    相关问题