【问题标题】:Binding ComboBox to DataTable (WinForms c#)?将 ComboBox 绑定到 DataTable(WinForms c#)?
【发布时间】:2014-04-19 20:13:35
【问题描述】:

我有一个从DataTable 填充我的ComboBox 的方法:

public string populateCompanyTransSellingEntityLookUp(ref System.Windows.Forms.ComboBox Combo, string Id, Contract Contract)
    {
        SqlCommand _comm = new SqlCommand();
        _comm.Parameters.AddWithValue("@id", Id);
        _comm.CommandText = "SELECT [name] FROM dbo.fnGetList(@id) ORDER BY [name]; ";   
        _comm.Connection = _conn;
        _comm.CommandTimeout = _command_timeout;

        DataTable dt = new DataTable();
        try
        {
            SqlDataReader myReader = _comm.ExecuteReader();
            dt.Load(myReader);

            Combo.DataSource = dt;
            Combo.DisplayMember = "name";

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["name"].ToString() == Contract.Company_Name.ToString())
                {                        
                    Combo.Text = dr["company_int_name"].ToString();
                }
            }
        }
        catch
        {
            MessageBox.Show("Unable to populate Company Name LookUp");
        }


        return "";
    }

我将保存的值 Contract.Company_Name 传递到 forEach 循环中,以便从 DataTable 中找到我所需的 SelectedItemComboBox 填充了来自 Combo.Datasource =dt; 的我的 DataTable 值,但未设置我的选定项目。代码编译无异常。如果我删除了Datasource = dt;, theSelectedItemis set no problem. Why is theDatasourceoverriding mySelectedItem`,我的绑定是否遗漏了什么?

谢谢大家

【问题讨论】:

  • 像这样设置 ValueMember:Combo.ValueMember = "name";
  • 不幸的是仍然没有修复...

标签: c# winforms combobox datatable


【解决方案1】:

首先,您必须确定设置 valueMember。然后您可以设置 selectedValue 属性而不是 SelectedItem。项目是一个数据源记录。所以在你的情况下,它将是SelectedItem = dr!但我不确定这是否有效。

【讨论】:

    【解决方案2】:

    试试这个:

    Combo.SelectedItem = dr;
    

    【讨论】:

    • 已修复。将 SelectedItem 全部取出并设置 Combo.Text = dr["company_int_name"].ToString();在 forEach 中。不确定为什么 SelectedItem 不会绑定?有问题的编辑代码:)
    • 在我看来,这是完成任务的一种丑陋方式。您最好使用 SelectedValue 属性。您应该考虑使用 IList 而不是 DataTable。在复杂的情况下更容易处理。例如,您可以使用 Lambda 语句。
    【解决方案3】:

    我建议使用SelectedValue,这样您就不需要“手动”循环遍历值。

    此外,您不需要使用“重量级”DataTable,您只需要一组字符串值。

    private IEnumerable<string> LoadNames(string id)
    {
        var query = "SELECT [name] FROM dbo.fnGetList(@id) ORDER BY [name]";
    
        using (var connection = new SqlConnection("connectionString")
        using (var command = new SqlCommand(query, connection)
        {
            // 36 is the size of the VarChar column in database(use your value)
            command.Parameters.Add("@id", SqlDbType.VarChar, 36).Value = id;
    
            connection.Open();
            using (var reader = command.ExecuteReader())
            {
                var names = new List<string>();
                while(reader.Read())
                {
                    names.Add(reader.GetString(0));
                }
    
                return names;
            }
        }
    }
    
    
    public void Populate(ComboBox combobox, string id, Contract contract)
    {
        combobox.DataSource = LoadNames(id);
        combobox.SelectedValue = contract.Copmpany_Name.ToString();
    }
    

    注意事项:

    1. 处理所有处理外部资源的对象(SqlConnectionSqlCommandSqlDataReader
    2. 使用有关类型的精确信息创建SqlParameter,因为字符串对于提供数据库中列的大小很重要。此信息将提高服务器端的 SQL 查询性能。
    3. 不要将组合框作为引用传递,populate 方法不会创建新实例,而只会使用给定的 ComboBox 实例。

    【讨论】:

      猜你喜欢
      • 2013-05-26
      • 2015-01-30
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多