【发布时间】:2020-10-30 13:04:40
【问题描述】:
我有一个DataTable 使用以下代码绑定到dataGridView:
dataGridView1.DataSource = ReducedColTable;
有时我想将选定的行移动到另一个表中。 所以这里是循环:
List<DataGridViewRow> rows = (from DataGridViewRow row in dataGridView1.SelectedRows
where !row.IsNewRow
orderby row.Index
select row).ToList<DataGridViewRow>();
foreach (DataGridViewRow item in rows)
{
DataRow newRow = dtarget.Rows.Add();
newRow.SetField("artiste", item.Cells[0].Value);
newRow.SetField("album", item.Cells[1].Value);
newRow.SetField("song", item.Cells[2].Value);
newRow.SetField("year", item.Cells[3].Value);
newRow.SetField("file_path", item.Cells[4].Value);
newRow.SetField("file_size", item.Cells[5].Value);
dataGridView1.Rows.RemoveAt(item.Index);
}
Ps:我没有找到将行复制到全局声明的新表 (dtarget) 的方法,因此方法 col by col。
DataTable dtarget = new DataTable();
我的问题是最后一行是从 DataGridView 中删除该行,但不是从原始表中删除 (ReducedColTable)
任何提示如何实现这一点?
【问题讨论】:
-
从数据源(您的数据表)中删除记录(行)。如果您需要一个与原始数据表相同的数据表,那么
Clone()原始数据表。您可以获取一个 DataRow 对象并将其复制到克隆的 DataTable 中。 -
好吧,我想要的是能够将行从原始移动到目标,所以克隆不会正常工作?
-
您克隆一个 DataTable 以拥有一个具有相同结构(和约束)的对象。然后,您可以在需要时将 DataRow 从原始 DT 复制/移动到克隆。与删除 DataRow 无关,您仍然需要将其从 DataSource 中删除,而不是从 Control 中删除。
-
好的,谢谢,我会试试这个,以避免用 col 填充目标 dt col。谢谢
标签: c# winforms datatable datagridview