Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert row in middle of DataGridView (C#)

I would like to insert a new DataGridViewRow into my DataGridView at a specific index. If I just create a new Row like

DataGridViewRow dgwr = new DataGridViewRow();
datagridview1.Rows.Insert(index, dgwr);

I will not get the "settings" of the DataGridView, like for example my "Cells" will be 0. This does not happen if I use.

DataGridView1.Add();

But then again, then I cant chose where in the list I would like my post...

Is there anyway to combine these advantages?

/Nick

like image 893
Nick3 Avatar asked Mar 26 '12 06:03

Nick3


People also ask

How to insert row in DataGridView c#?

DataGridViewRow dgwr = new DataGridViewRow(); datagridview1. Rows.

How to add blank row in GridView c#?

For adding new row to the gridview has some concern. Do you previously have some datasource in the gridview or not ? If you have some datasource previously and then you need to save the datasource in viewstate and before adding a new row you need to extract previous data in the gridview and then add a new row.


2 Answers

grid.Rows.Insert(index, 1);
var addedRow = grid.Rows[index];

This inserts 1 empty templated row at 'index', and then simply accesses row in 'index'. The 2nd line is for accessing the just-now-added row.

Can also shorten if you know your wished row values with:

grid.Rows.Insert(index, FirstName, LastName, BirthDate, Etc);

Just have to make sure it is synced with the columns order in the grid, and it makes the row automatically with these fields.

like image 89
SimpleVar Avatar answered Sep 18 '22 15:09

SimpleVar


DataGridView and DataGridRowView are just visual representations of your data source and one row in your data source. A new visual row should be displayed in your DataView after a new row is added to your data source.

If you want to get the view row when new row is added handle RowsAdded event.

like image 30
Karel Frajták Avatar answered Sep 22 '22 15:09

Karel Frajták