在 DataGridView (C#) 中间插入行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9867550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:59:55  来源:igfitidea点击:

Insert row in middle of DataGridView (C#)

c#datagridview

提问by Nick3

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

我想在特定索引处将新的 DataGridViewRow 插入到我的 DataGridView 中。如果我只是创建一个新行

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.

我不会得到 DataGridView 的“设置”,例如我的“单元格”将为 0。如果我使用,则不会发生这种情况。

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

/缺口

采纳答案by SimpleVar

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.

这会在“索引”处插入 1 个空模板行,然后简单地访问“索引”中的行。第二行用于访问刚刚添加的行。

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.

只需确保它与网格中的列顺序同步,并自动使用这些字段生成行。

回答by Karel Frajták

DataGridViewand DataGridRowVieware 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.

DataGridView并且DataGridRowView只是您的数据源和数据源中的一行的可视化表示。将新行添加到数据源后,应在 DataView 中显示新的可视行。

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

如果要在添加新行时获取视图行,请处理RowsAdded事件。