将ComboBox绑定到数据表(WinForms c#)

本文关键字:WinForms 数据表 ComboBox 绑定 | 更新日期: 2023-09-27 17:50:12

我有一个方法从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;,但我选择的项目没有被设置。代码可以正常编译。如果我删除Datasource = dt;, the SelectedItem is set no problem. Why is the数据源overriding my SelectedItem ',是否有一些我错过了我的绑定?

谢谢所有的

将ComboBox绑定到数据表(WinForms c#)

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

试试这个:

Combo.SelectedItem = dr;

我建议使用SelectedValue,这样你就不需要手动遍历值了。

你也不需要使用"heavy-weight"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. 处理所有处理外部资源(SqlConnection, SqlCommandSqlDataReader)的对象
  2. 创建SqlParameter,包含关于类型的精确信息,因为字符串在数据库中提供列的大小是很重要的。此信息将提高服务器端的SQL查询性能。
  3. 不要传递combobox作为引用,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 "";
    }