异常:设置DataSource属性时,无法修改项集合 [英] Exception : Items collection cannot be modified when the DataSource property is set

查看:810
本文介绍了异常:设置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 

这篇关于异常:设置DataSource属性时,无法修改项集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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