insert item in combobox after binding it from a Dataset in c#
You have to Insert to the object you are databinding to rather than to the combobox. You can't insert directly into the combobox.
You can use this:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("CategoryName");
DataRow dr = dt.NewRow();
dr["CategoryName"] = "Select";
dr["ID"] = 0;
dt.Rows.InsertAt(dr, 0);
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
cmbCategory.DataSource = dt;
cmbCategory.SelectedIndex = 0;
This is very straight forward example.
You cannot add items to a ComboBox
after binding it to a data source. To add or remove items from a ComboBox
with a bound data source, you have to do it through data source itself.
You can insert a DataRow
into your table and it will be automatically added to your ComboBox
. Try the following:
DataRow dr = dsCat.Tables[0].NewRow();
dr["CategoryName"] = "Select";
dr["ID"] = 123;// Some ID
dsCat.Tables[0].Rows.Add(dr);