gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:25 25 4
gpt4 key购买 nike

我正在尝试将第一个值作为“选择一个”插入/添加到我在 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);

关于c# - 在 C# Windows 中设置 DataSource 属性时无法修改项集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31187979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com