Programatically add a gridViewrow in c#

57 Views Asked by At
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "AbC";
row.Cells[1].Value = 123;
dataGridView1.Rows.Add(row);

Previously I used to add new rows using above code. But now It gives error

Index was out of range. Must be non-negative and less than the size of the collection.

1

There are 1 best solutions below

0
Mustafa Ozbalci On BEST ANSWER

For the first entry you need to have a row in your datagridview. If you are not allowing the user to add new rows manually that means there is no row to clone. Then you allow user to add new rows first that will create an empty row to enter data then you will be able to clone that one. Later you can disable adding new rows if you want

dataGridView1.AllowUserToAddRows=true;
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "AbC";
row.Cells[1].Value = 123;
dataGridView1.Rows.Add(row);
dataGridView1.AllowUserToAddRows=false;