Skip to main content
 首页 » 编程设计

c#之在 C# Windows 中设置 DataSource 属性时无法修改项集合

2024年02月06日28me-sa

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

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

我知道我已经将 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...!!"; 
        } 
    } 

请。给我这个问题的解决方案。

请您参考如下方法:

在绑定(bind)到作为数据源的测试之前,您需要将“选择一个”值添加到测试字典中。

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

然后

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