如何将数据库值绑定到Windows Appliation中的组合框 [英] How to bind Database values to combo box in Windows Appliation

查看:226
本文介绍了如何将数据库值绑定到Windows Appliation中的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Windows应用程序中使用Combobox,并从数据库绑定值到组合框如下所示

I am Using Combobox in my Windows application and binding values to combo box from database as show below

public void LoadDatsbaseNames()
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        using (SqlDataAdapter da = new SqlDataAdapter("SELECT name FROM sys.databases ORDER BY name", connection))
        {
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataRow dr;
            dr = dt.NewRow();
            dr.ItemArray = new object[] { 0, "---Select--" };
            dt.Rows.InsertAt(dr, 0);
            cbDBName.DisplayMember = "name";
            cbDBName.DataSource = dt;
            connection.Close();
        }
    }
}

错误

Input array is longer than the number of columns in this table.


推荐答案

using (SqlDataAdapter da = new SqlDataAdapter("SELECT name FROM sys.databases ORDER BY name", connection))
    {
        DataTable dt = new DataTable();
        da.Fill(dt);
        cbDBName.DisplayMember = "name";
        cbDBName.DataSource = dt;
        connection.Close();
    }

此外,您不需要手动关闭连接,因为您使用使用语句,它会处理这个。

Also you do not need to close connection manually because you are using using statement it will take care of this.

这篇关于如何将数据库值绑定到Windows Appliation中的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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