繁体   English   中英

如何在数据绑定时以编程方式向 datagridview 添加一行?

[英]How to programmatically add a row to a datagridview when it is data-bound?

如果绑定到数据源(数据表),如何向 datagridview 控件添加一行? 谢谢!

在数据表中添加一行,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);
  • 创建一个与要在网格中显示的数据相对应的类(相同的属性)
  • 在您的数据绑定函数中,获取您的查询结果,但将结果放在一个列表中(或任何适合您和数据绑定的 IEnumerable)
  • 根据您的需要创建另一个对象并将其添加到您的列表中
  • 绑定列表

// 我操作了一个绑定列表。 在这里,我按顺序向下移动一行。

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

如果我尝试将行添加到 datagridview 本身,我使用数据集将行添加到 datagridview,它说它不会因为它的数据绑定而以编程方式添加行。

// 在Form Load中可以找到datagridview的DataSet

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 添加行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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