Click here to Skip to main content
15,942,964 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi,

I have a small problem with Combobox Data binding.
I am binding data to combobox from database by using the following code.
C#
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.
C#
cmbUnit.Items.Insert(0, "Select");

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
Posted
Updated 10-Mar-11 22:02pm
v2
Comments
Tarun.K.S 11-Mar-11 4:04am    
Use <pre> tags to wrap you code.

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.
 
Share this answer
 
v3
Comments
Dalek Dave 11-Mar-11 4:52am    
Not what the op needs, he wants to add AFTER binding.
jbgalanza 11-Mar-11 5:38am    
I already edited it. Thanks!
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";
 
Share this answer
 
Comments
Richard Deeming 14-Aug-15 10:05am    
Why have you posted a new "solution" to a solved question from over four years ago?!

Your "answer" doesn't even answer the question that was asked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900