繁体   English   中英

从数据库获取数据到ComboBox

[英]Get Data from database to ComboBox

短一个。

一个名为ComDet的数据库,其列为cID(PK),cName,cDet,mainCate(FK),Subcat(FK)。

这假设是将数据从表ComDet获取到组合框。

DataSet ds2;

private void searchBtn_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
    conn.Open();

    SqlDataAdapter daSearch = new SqlDataAdapter("SELECT cName FROM ComDet", conn);
    ds2 = new DataSet();
    daSearch.Fill(ds2, "daSearch");
    ListU.ValueMember = "cName";
    ListU.DataSource = ds2.Tables["ComDet"];
    ListU.DropDownStyle = ComboBoxStyle.DropDownList;
    ListU.Enabled = true;
}

但是它没有用..我在哪里出错了? 组合框中未显示数据库表ComDet中的Data(cName)。 -

问题:您正在将数据库表名称ComDet分配为DataSource而不是DataTable名称daSearchComboBox

解决方案:您需要为ComboBox分配有效的DataTable名称作为Datasource

替换为:

ListU.DataSource = ds2.Tables["ComDet"];

有了这个:

ListU.DataSource = ds2.Tables["daSearch"];  

(要么)

ListU.DataSource = ds2.Tables[0];

完整的代码:

DataSet ds2;

private void searchBtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();

SqlDataAdapter daSearch = new SqlDataAdapter("SELECT cName FROM ComDet", conn);
ds2 = new DataSet();
daSearch.Fill(ds2, "daSearch");
ListU.ValueMember = "cName";
ListU.DataSource = ds2.Tables["daSearch"];
ListU.DropDownStyle = ComboBoxStyle.DropDownList;
ListU.Enabled = true;
}

所以这个问题问如何从数据库中获取数据到combobox 就个人而言,我发现使用DataSet类是不可取的-它很容易出现错误,例如asker在此遇到的错误。

试试这种方法。 读取所有的cNameList并绑定ListComboBox 简单易读的代码。 using语句的using还可以确保有效释放非托管资源。

private void searchBtn_Click(object sender, EventArgs e)
{
    var list = new List<string>();
    using (var conn = new SqlConnection())
    {
        conn.ConnectionString = 
            "Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
        conn.Open();
        using (var cmd = new SqlCommand("SELECT cName FROM ComDet", conn))
        {
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    list.Add(Convert.ToString(reader["cName"]));
                }
            }
        }
   }
   ListU.DataSource = new BindingSource(list, null);
   ListU.DropDownStyle = ComboBoxStyle.DropDownList;
   ListU.Enabled = true;
}

暂无
暂无

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

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