将组合框绑定到数据表(WinForms c#)?

x7rlezfr  于 2022-12-23  发布在  C#
关注(0)|答案(4)|浏览(174)

我有一个从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;, the SelectedItem is set no problem. Why is the Datasource overriding my SelectedItem ',并且是否存在我'我的装订没打好?
谢谢大家

bmp9r5qi

bmp9r5qi1#

首先你必须设置valueMember,然后你可以设置selectedValue属性来代替SelectedItem。Item是一个数据源记录,所以在你的例子中它应该是SelectedItem = dr!但是我不确定这是否有效。

erhoui1w

erhoui1w2#

试试这个:

Combo.SelectedItem = dr;
6g8kf2rb

6g8kf2rb3#

我建议使用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
1.使用有关字符串类型的精确信息创建SqlParameter对于提供数据库中列的大小非常重要。此信息将提高服务器端的SQL查询性能。
1.不要将组合框作为引用传递,populate方法不会创建新示例,而只使用给定的ComboBox示例。

fzwojiic

fzwojiic4#

谢谢你的帮助,我编辑了代码,因为我的问题要琐碎得多。

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 "";
    }

相关问题