Items collection cannot be modified when the DataSource property is set.
Screenshot is given below:
Lets try to make this error. After that we will resolve this problem. To make this error first add a form in your project then add a combobox control within this form & run the below code:
private void Form1_Load(object sender, EventArgs e) { DataTable oTable = new DataTable("Article"); //Add DataTable column dynamically/run time/on the fly. oTable.Columns.Add(new DataColumn("ID", typeof(System.Int64))); oTable.Columns.Add(new DataColumn("Title", typeof(System.String))); //Add DataTable rows dynamically/run time/on the fly. oTable.Rows.Add(1001, "DataTable Engineering"); oTable.Rows.Add(1002, "Event Calendar"); oTable.Rows.Add(1003, "Master Detail Data"); comboBox1.DataSource = oTable; comboBox1.DisplayMember = "Title"; // this line will generate error comboBox1.Items.Insert(0, "Select"); }
Here you can test by using a database for simplicity i use datatable.
Now solution:
In such type of scenario i always modify the datasource like datatable first. After that i bind this datasource into the combobox. So to resolve this problem my workaround is given below:
private void Form1_Load(object sender, EventArgs e) { DataTable oTable = new DataTable("Article"); //Add DataTable column dynamically/run time/on the fly. oTable.Columns.Add(new DataColumn("ID", typeof(System.Int64))); oTable.Columns.Add(new DataColumn("Title", typeof(System.String))); //Add DataTable rows dynamically/run time/on the fly. oTable.Rows.Add(1001, "DataTable Engineering"); oTable.Rows.Add(1002, "Event Calendar"); oTable.Rows.Add(1003, "Master Detail Data"); // Use insertAt method to force to enter data DataRow oRow = oTable.NewRow(); oRow["Title"] = "Select"; oTable.Rows.InsertAt(oRow, 0); comboBox1.DataSource = oTable; comboBox1.DisplayMember = "Title"; }
Happy coding.
No comments:
Post a Comment
Write your Comment: