Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound

后端 未结 6 967
囚心锁ツ
囚心锁ツ 2020-11-29 10:02

First of all, I looked up this related question in here but the solution dataGridView1.Rows.Add() doesn\'t work in my case.

In my Datagridview, I have

6条回答
  •  臣服心动
    2020-11-29 10:39

    After adding a new row, you have to set the row index in boundary of row count. You have to do these steps.

    1. First, add row in DataGridView:

      dataGridView1.Rows.Add();
      
    2. Second, set new row index to count - 1:

      int RowIndex = dataGridView1.RowCount - 1;
      
    3. Then at last, set the controls values in it:

      DataGridViewRow R = dataGridView1.Rows[RowIndex];
      R.Cells["YourName"].Value = tbName.Text;
      

    And if your datagrid's source is datattable you have to add row in that table.Give new values to the newly added row in data table and at last rebind the datagrid with updated datatable.

        DataRow row = dt.NewRow();  
        row["columnname"] = tbName.Text.toString();  
        dt.Rows.Add(row);
        dt.AcceptChanges();  
    
       dataGridView1.DataSource = dt;  
       dataGridView1.DataBind();
    

    Check if you have set the index of the new row properly. Perhaps that's why you are getting this error.

提交回复
热议问题