0
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.

Abbas
  • 9
  • 6
  • Are you 100% sure the grid has at least two columns and at least one row? Which line of code throws the error? – JohnG Jun 23 '22 at 14:06
  • ` DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone(); ` this line gives error – Abbas Jun 23 '22 at 14:11
  • how will it contain a row when we are adding it programatically ?? – Abbas Jun 23 '22 at 14:13
  • 1
    _"how will it contain a row when we are adding it programatically ?? "_ ... this is true. So how could you "clone" a row that isn't there? ... `DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();` ... ? ... – JohnG Jun 23 '22 at 14:14
  • then how it is working on a different form. So what's the proper way to add row programmatically ? – Abbas Jun 23 '22 at 14:16
  • I can only guess that the other code HAS at least one row in the grid. Is the grid’s `AllowUserToAddRows` property set to `true`? There a few ways you can add rows and it depends on if the grid uses a data source. If the grid has no data source and there are at least two columns in the grid, then the code… `dataGridView1.Rows.Add(“ABC”, 123);` … should work. – JohnG Jun 23 '22 at 14:26
  • thanks for the help,The problem was I unchecked the Enable Adding property in gridview and one can not add row programmatically to data bound gridview – Abbas Jun 23 '22 at 14:53

1 Answers1

0

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;