在 C# Windows 中设置 DataSource 属性时无法修改项目集合 [英] Items collection cannot be modified when the DataSource property is set in C# Windows

查看:40
本文介绍了在 C# Windows 中设置 DataSource 属性时无法修改项目集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将第一个值作为选择一个"插入/添加到 C# Windows 窗体应用程序中的组合框.组合框样式为DropDownList".

I am trying to Insert/Add first value as "Select One" to my combobox in C# Windows Forms Application. Combo box style is "DropDownList".

我正在从数据库中获取城市数据并绑定组合框.

I am fetching cities data from database and binding combobox.

我知道我已经将 1 个数据源设置为组合框并再次尝试添加 .我想动态添加选择一个",如何做到这一点?

I know that I already set 1 datasource to combobox and again trying to add . I want to add "Select One" dynamically ,How to do this?

这是填充城市代码.

    public void Fill_CitiesDDL()
    {
        try
        {
            cmbCity.Items.Clear();
            DataSet ds = new DataSet();
            ds = Select_Cities();
            ds.DataSetName = "Tbl_City";
            if (ds.Tables.Count > 0)
            {
                if (ds.DataSetName == "Tbl_City" && ds.Tables[0].Rows.Count > 0)
                {
                    Dictionary<string, string> test = new Dictionary<string, string>();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        test.Add(ds.Tables[0].Rows[i]["City_Name"].ToString(), ds.Tables[0].Rows[i]["City_Id"].ToString());
                    }
                    this.cmbCity.DataSource = new BindingSource(test, null);
                    this.cmbCity.DisplayMember = "Key";
                    this.cmbCity.ValueMember = "Value";
                    this.cmbCity.Items.Add("Select One ");--->Error is Coming at this Point
                }
                else
                {
                    lblEmployerError.Text = "No data for City";
                }
            }
            else
            {
                lblEmployerError.Text = "City Table does not exists";
            }
        }
        catch (NullReferenceException nr)
        {

            lblEmployerError.Text="Null value exception caused, try again later..!!";
        }
        catch (SqlException sql1)
        {

            lblEmployerError.Text="Connection to server failed or network problem..!!";
        }
        catch (Exception ex)
        {

            lblEmployerError.Text="Fatal error catched, contact system administrator...!!";
        }
    }

请.给我解决这个问题的方法.

Pls. give me solutions to this problem.

推荐答案

在绑定到测试作为数据源之前,您需要将Select One"值添加到测试字典中.

You will need to add your "Select One" value to the test dictionary prior to binding to the test as your data source.

test.Add("Select One ","Select One ");

然后

this.cmbCity.DataSource = new BindingSource(test, null);

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

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