当数据绑定时,如何以编程方式向DataGridView添加行?

12

如果数据网格视图控件绑定到数据源(数据表),我该如何添加一行?谢谢!


1
向DataTable添加一行 - Ralf
这个有帮助吗?https://dev59.com/tGHVa4cB1Zd3GeqPlUgT?rq=1 - Sriram Sakthivel
可能是c#如何以编程方式向datagridview添加新行的重复问题。 - Cody Gray
4个回答

20

向数据表中添加一行,DataGridView 将自动更新:

DataTable dt = myDataGridView.DataSource as DataTable;
//Create the new row
DataRow row = dt.NewRow();

//Populate the row with data

//Add the row to data table
dt.Rows.Add(row);

2
请注意,您还可以在顶部添加:dt.Rows.InsertAt(row, 0); - TaW
最佳答案! - CodeAlo

0
  • 创建一个与您希望在网格中显示的数据相对应的类(具有相同的属性)
  • 在您的数据绑定函数中,获取查询结果,但将结果放入列表中(或任何适合您和数据绑定的IEnumerable)
  • 根据您的需求创建并添加另一个对象到您的列表中
  • 绑定列表

0

我使用数据集将行添加到DataGridView中,如果我尝试向DataGridView本身添加行,则会提示它不接受以编程方式添加行,因为它是数据绑定的。

// DataGridView的数据集可以在窗体加载中找到

advokathusetDataSet.Kunde.Rows.Add(DeletedRowsList[lastindex].Cells[0].Value, DeletedRowsList[lastindex].Cells[1].Value, DeletedRowsList[lastindex].Cells[2].Value, DeletedRowsList[lastindex].Cells[3].Value, DeletedRowsList[lastindex].Cells[4].Value, DeletedRowsList[lastindex].Cells[5].Value, DeletedRowsList[lastindex].Cells[6].Value);

// 将Datagridview中的行添加到列表中,将列表中的行添加到Datagridview中 - 如何使用列表向Datagridview添加行


0

// 我操作了一个绑定列表。这里我将一行向下移动。

BindingList<MyType> lst = (BindingList<MyType>)DataGridView.DataSource;
MyType objQcc = lst[rowIndex];
lst.Insert(rowIndex + 2, objQcc);
lst.RemoveAt(rowIndex);        

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接