user2901955
user2901955

Reputation: 103

Items collection cannot be modified when the DataSource property is set. c#

I am getting the error while I am trying to insert a new item into combo box

Error: Items collection cannot be modified when the DataSource property is set.

string connectionstring = "MultipleActiveResultSets=True;Data Source=ECSTSRD;Initial Catalog=PMIDB;User ID=pnpuser;Password=pnpuser123";
sqlConnection myconnection = new SqlConnection(connectionstring);

myconnection.Open();
string custPOsql = "INSERT INTO cust_po (cust_code, po_no) VALUES (@cust_code, @po_no)";
       SqlCommand custPOcom = new SqlCommand(custPOsql, myconnection);
       custPOcom.Parameters.AddWithValue("@cust_code", cboCustCode.Text);
       custPOcom.Parameters.AddWithValue("@po_no", cboPO.Text);
       custPOcom.ExecuteNonQuery();
       MessageBox.Show("Insert Successfully", "Insert");
       cboPO.Items.Add(cboPO.Text);

FYI, I bind the data source of PO combobox in form load.

I have found few similar question in stackoverflow as well as others forums, the way they mention is using cboPO.Items.Add(cboPO.Text) to add new item into combo box, but I could not use it as error shown.

Do anyone know what is the problem, please help.

Thanks in advance.

Upvotes: 0

Views: 8441

Answers (2)

Jade
Jade

Reputation: 2992

Your cboPO control is already bind with datasource that display data

use this if want to add rows in your combobox

DataTable dt = cboPO.Datasource;
DataRow dr = dt.NewRow();
dr["ColumnName"/Index number] = cboPO.Text;

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66439

You can either use cboPO.Items.Add(), or you can bind to a list as you appear to have done.

"FYI, I bind the data source of PO combobox in form load."

It's telling you that you cannot bind the combo box to a data source, and then try to add items directly to the combo box too. It's an either/or thing - you can't do both.

You'll have to add items to whatever object you originally bound to the combo box in your Form_Load event, and then they should be reflected in the combo box automatically.

Upvotes: 0

Related Questions