【问题标题】:Items collection cannot be modified when the DataSource property is set in C# Windows在 C# Windows 中设置 DataSource 属性时无法修改 Items 集合
【发布时间】:2015-07-02 14:55:42
【问题描述】:

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

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

我知道我已经将 1 个数据源设置为组合框并再次尝试添加 .我想动态添加“选择一个”,怎么做?

这是填充城市代码。

    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...!!";
        }
    }

请。给我解决这个问题。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

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

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

    然后

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

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 2010-10-29
      • 2017-02-23
      相关资源
      最近更新 更多