简体   繁体   中英

Programatically add a gridViewrow in c#

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM