C#从数据库表中填充一个ComboBox [英] C# Populate a ComboBox from table in database

查看:137
本文介绍了C#从数据库表中填充一个ComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个被称为 combobox1 组合框,我想与 ID 来填充它的价值和名称的显示名称。我搜索,阅读一些教程,发现这个代码在Form Load事件中使用,但它不填充列表。我看到一个空的下拉列表。的,我错在何处任何想法?



在我的数据库类我有这个功能。

 公共静态无效FillDropDownList(字符串查询,System.Windows.Forms.ComboBox DropDownName)
{
SqlDataReader的博士;

的SqlConnection MyConnection的=新的SqlConnection(CONNECTION_STRING);

{
myConnection.Open();
}
赶上(例外五)
{
Console.WriteLine(e.ToString());
}

//检查下拉上是否已存在的项目。如果是,倒空。
如果(DropDownName.Items.Count大于0)
DropDownName.Items.Clear();

的SqlCommand CMD =新的SqlCommand(查询,MyConnection的);
博士= cmd.ExecuteReader();

而(dr.Read())
DropDownName.Items.Add(博士[0]的ToString());

Console.Write(DropDownName.Items.Add(DR [0]的ToString()));
dr.Close();
}

在我的表单我叫它为



 私人无效sales_record_Load(对象发件人,EventArgs五)
{
的SqlConnection CON =新的SqlConnection(DBUtils.CONNECTION_STRING);
DBUtils.FillDropDownList(SELECT标识,从农场名称,comboBox1);
}


解决方案

我的建议 - 使用.NET内置功能尽可能,不处理数据手工绑定(这是您想在你的代码做):




  1. 使用的executeQuery从数据库中提取数据的DataTable。

  2. 设置DropDownName.DataSource = yourDataTable。

  3. 设置DropDownName.ValueMember =ID。

  4. 设置DropDownName.DisplayMember =名称。



所以,你的代码将类似于这样的:

 公共静态无效FillDropDownList(字符串查询,System.Windows.Forms.ComboBox DropDownName)
{
的DataTable dt的;

使用(VAR CN =新的SqlConnection(CONNECTION_STRING))
{
cn.Open();


{
的SqlCommand CMD =新的SqlCommand(查询,CN);
DT = cmd.ExecuteQuery();
}
赶上(SQLEXCEPTION E)
{
Console.WriteLine(e.ToString());
的回报;
}
}

DropDownName.DataSource = DT;
DropDownName.ValueMember =ID;
DropDownName.DisplayMember =姓名;
}



注意我是如何改变的异常类型为的SQLException ,所以我们只是在寻找数据库错误。一切将炸毁。我不记得任何情况下,当 myConnection.Open(); 将抛出一个异常,所以你的try块不是非常有用。在我的try子句声明 - 它的executeQuery 里面,这很可能会失败。



修改。 无需关闭连接使用使用结构的时候终于块。因此,它可以被删除 - 和你的代码变得因此更紧凑


I have a combobox which is called combobox1, which I want to populate it with id as value and Name as display name. I searched and read some tutorial and found this code to use in Form load event, but it doesn't populate the list. I see an empty dropdown. Any ideas of where I am wrong?

In my database class I have this function.

public static void FillDropDownList(string Query, System.Windows.Forms.ComboBox DropDownName)
{
   SqlDataReader dr;

   SqlConnection myConnection = new SqlConnection(CONNECTION_STRING);
   try
   {
      myConnection.Open();
   }
   catch (Exception e)
   {
      Console.WriteLine(e.ToString());
   }

   // Check whether the Drop Down has existing items. If YES, empty it.
   if (DropDownName.Items.Count > 0)
      DropDownName.Items.Clear();

   SqlCommand cmd = new SqlCommand(Query, myConnection);
   dr = cmd.ExecuteReader();

   while (dr.Read())
      DropDownName.Items.Add(dr[0].ToString());

   Console.Write(DropDownName.Items.Add(dr[0].ToString()));
   dr.Close();
}

In my form i call it as

private void sales_record_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(DBUtils.CONNECTION_STRING);
    DBUtils.FillDropDownList("select id,Name from Farms", comboBox1);
}

解决方案

My advice - use .NET built-in functionality as much as possible, and don't handle data binding manually (which is what you are trying to do in your code):

  1. Use ExecuteQuery to pull a DataTable from database.
  2. Set DropDownName.DataSource = yourDataTable.
  3. Set DropDownName.ValueMember = "id".
  4. Set DropDownName.DisplayMember = "Name".

So your code would look similar to this:

public static void FillDropDownList(string Query, System.Windows.Forms.ComboBox DropDownName)
{
  DataTable dt;

  using (var cn = new SqlConnection(CONNECTION_STRING))
  {
    cn.Open();

    try
    {
      SqlCommand cmd = new SqlCommand(Query, cn);
      dt = cmd.ExecuteQuery();
    }
    catch (SqlException e)
    {
      Console.WriteLine(e.ToString());
      return;
    }
  }

  DropDownName.DataSource = dt;
  DropDownName.ValueMember = "id";
  DropDownName.DisplayMember = "Name";
}

Notice how I changed exception type to SqlException, so we are only looking for database errors. Everything else will blow up. I don't remember any situation when myConnection.Open(); would throw an exception, so your try block is not very useful. Notice in my try clause - it has ExecuteQuery inside it, which is likely to fail.

EDIT: There is no need to close connection in the finally block when using the using construct. So it can be removed - and your code becomes more compact as a result.

这篇关于C#从数据库表中填充一个ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆