如何在Windows应用程序中将数据库值绑定到组合框 [英] How to bind Database values to combo box in Windows Application

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

问题描述

我正在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();
        }
    }
}

但是上述方法显示了错误

But the Above Method showing an error


输入数组的长度大于此表中的列数。

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


推荐答案

如果只想绑定组合框,则不需要创建DataRow,因为DataTable已经填充了数据,您只需将其与组合框绑定即可。

You do not need to create DataRow if you only want to bind combobox because DataTable is already filled with data you just only bind it with combobox.

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应用程序中将数据库值绑定到组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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