I had combobox in Windows Form which is bound to data from database.
I did this well but when I tried to add first item <-Please select Category-> befor the data from database this error apeared
(Items collection cannot be modified
when the DataSource property is set)
in CBParent.Items.Insert(0,
“-select-“);
public Category()
{
InitializeComponent();
CategoryParent();
}
private void CategoryParent()
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
CBParent.Items.Insert(0, "-select-");
}
}
You would have to add the item to the data source itself, i.e in the SQL query, because as the error says, you cannot add items to the control if you have the datasource set.
One way would be to get your sql query do a union like this: