如何在绑定数据源后将新项添加到ComboBox中? [英] How to add new Item into ComboBox after binding with a Datasource?

查看:71
本文介绍了如何在绑定数据源后将新项添加到ComboBox中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我对Combobox数据绑定有一个小问题。

我通过使用数据库将数据绑定到数据库中以下代码。

Hi,

I have a small problem with Combobox Data binding.
I am binding data to combobox from database by using the following code.

SqlDataAdapter da1 = new SqlDataAdapter("select * from Table1", con);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
cmbUnit.DataSource = ds1.Tables[0];
cmbUnit.DisplayMember = "UnitName";





之后我想使用以下代码将新项目插入到组合框中。



After that I want to Insert New item to combobox by using the following code.

cmbUnit.Items.Insert(0, "Select");



但它显示的错误是设置数据源属性时无法修改项目集合。

任何人都可以建议我只使用C#Combobox来解决这个问题。





谢谢

Pavan


But it is showing an error that "Item Collection can't be modified when the datasource property is set".
Can anyone please suggest me how to resolve that problem by using C# Combobox only.


Thanks
Pavan

推荐答案





你可以这样做。

Hi,

You can do like this.
System.Data.DataTable tbl = new System.Data.DataTable();
tbl.Columns.Add("UnitName");
tbl.Rows.Add("item 1");
tbl.Rows.Add("item 2");
DropDownList ddl = new DropDownList();
ddl.DataSource = tbl;
ddl.DataMember = "UnitName";
ddl.DataTextField = "UnitName";
ddl.DataBind();

//add new item
ddl.Items.Insert(0, new ListItem("inserted item"));





希望它能为您提供帮助。



Hope It will help you.


Conn obcon = new Conn( );

SqlConnection ob = new SqlConnection(obcon.strCon);

SqlDataAdapter da = new SqlDataAdapter();

da.SelectCommand = new SqlCommand();

da.SelectCommand.Connection = ob;

SqlCommand ds = da.SelectCommand;

ds.CommandText =Select *来自UserManagement;

ds.CommandType = CommandType.Text;

DataTable dt = new DataTable();

da.Fill(dt) ;

DataTable dtt = new DataTable();

dtt.Columns.Add(FullName);

dtt.Rows.Add( );

dtt.Rows [0] [FullName] =选择姓名;

for(int i = 0; i< dt.Rows.Count ; i ++)

{

dtt.Rows.Add();

dtt.Rows [i + 1] [FullName] = dt.Rows [i] [0] .ToString();

}

cmbFindUser。 DataSource = dtt;

cmbFindUser.DisplayMember =FullName;

cmbFindUser.ValueMember =FullName;
Conn obcon = new Conn();
SqlConnection ob = new SqlConnection(obcon.strCon);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand();
da.SelectCommand.Connection = ob;
SqlCommand ds = da.SelectCommand;
ds.CommandText = "Select* from UserManagement";
ds.CommandType = CommandType.Text;
DataTable dt = new DataTable();
da.Fill(dt);
DataTable dtt = new DataTable();
dtt.Columns.Add("FullName");
dtt.Rows.Add();
dtt.Rows[0]["FullName"] = "Select Name";
for (int i = 0; i < dt.Rows.Count; i++)
{
dtt.Rows.Add();
dtt.Rows[i + 1]["FullName"] = dt.Rows[i][0].ToString();
}
cmbFindUser.DataSource = dtt;
cmbFindUser.DisplayMember = "FullName";
cmbFindUser.ValueMember = "FullName";


这篇关于如何在绑定数据源后将新项添加到ComboBox中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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