在绑定数据库中的数据之前将项目添加到组合框 [英] Add an item to combobox before binding data from the database

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

问题描述

我有一个 Windows 窗体形式的组合框,可以从数据库中检索数据.我做得很好,但我想在数据库中的数据之前添加第一项 <-请选择类别->.我怎样才能做到这一点?我可以把它放在哪里?

I had a combobox in a Windows Forms form which retrieves data from a database. I did this well, but I want to add first item <-Please select Category-> before the data from the database. How can I do that? And where can I put it?

public Category()
{
    InitializeComponent();
    CategoryParent();

}

private void CategoryParent()
{
    using (SqlConnection Con = GetConnection())
    {
        SqlDataAdapter da = new SqlDataAdapter("Select Category.Category, Category.Id from Category", Con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        CBParent.DataSource = dt;
        CBParent.DisplayMember = "Category";
        CBParent.ValueMember = "Id";
    }
}

推荐答案

您可以像这样(首选)将默认文本添加到组合框的 Text 属性中:

You could either add the default text to the Text property of the combobox like this (preferred):

CBParent.Text = "<-Please select Category->";

或者,您可以直接将值添加到数据表中:

Or, you could add the value to the datatable directly:

da.Fill(dt);
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;

这篇关于在绑定数据库中的数据之前将项目添加到组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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