繁体   English   中英

将 ComboBox 绑定到 DataTable(WinForms c#)?

[英]Binding ComboBox to DataTable (WinForms c#)?

我有一个从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中找到我需要的SelectedItem ComboBox填充了来自Combo.Datasource =dt;的我的 DataTable 值但我选择的项目没有被设置。 代码编译无异常。 如果我删除Datasource = dt;, the SelectedItem is set no problem. Why is the is set no problem. Why is the数据源会overriding my SelectedItem`,我的绑定是否遗漏了什么?

谢谢大家

尝试这个:

Combo.SelectedItem = dr;

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

我建议使用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实例。

感谢您的帮助,我编辑了代码,因为我的问题更加微不足道。

public string populate_comboBox(ref System.Windows.Forms.ComboBox Combo)
    {
        SqlCommand _comm = new SqlCommand();

        //edited for a simple one column sql query 
        _comm.CommandText ="SELECT [Column] FROM dbo.SQL_Table ORDER BY [Column];";
        //MUST open sql connection to DB 
        SqlConnection conn = new SqlConnection(global_DB_String_Connection);
        conn.Open();
        _comm.Connection = conn;

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

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

            foreach (DataRow dr in dt.Rows)
            {
                //populates the combo box with query results
                Combo.Text = dr["ColumnName"].ToString();
            }
        }
        catch
        {
            Console.WriteLine("ComboBox Populate method has failed! ");
        }
        conn.Close();
        return "";
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM