异常:设置DataSource属性时,无法修改项集合

问题描述:

我在Windows窗体中的combobox绑定到数据库中的数据。

I had combobox in Windows Form which is bound to data from database.

我做得很好,但是当我试图添加第一项 befor数据库中的数据此错误出现

I did this well but when I tried to add first item <-Please select Category-> befor the data from database this error apeared


(设置DataSource属性时,不能修改项目集合

in CBParent.Items.Insert(0,
-select - );

(Items collection cannot be modified when the DataSource property is set) in CBParent.Items.Insert(0, "-select-");



    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";
CBParent.Items.Insert(0, "-select-");
            }
        }


必须将该项目添加到数据源本身,即在SQL查询中,因为如错误所示,如果您设置了数据源,则不能向控件添加项目。

You would have to add the item to the data source itself, i.e in the SQL query, because as the error says, you cannot add items to the control if you have the datasource set.

一种方法是让你的sql查询做这样的联合:

One way would be to get your sql query do a union like this:

Select Category.Category ,Category.Id from Category

UNION

SELECT 'Please select Category', 0