[英]How to copy Selected row from DataGridView to DataTable in C#
我有一個DataGridView和一個DataTable,我想執行兩步操作。第一步是將選定的行從DataGridView復制到DataTable進行進一步處理,第二步是從DataGridView中刪除該行。
注意:我想一個接一個地刪除多行,因此每次我將一行復制到DataTable中時,它都會進入下一個Datable行索引。
這是我用來從DataTable刪除選定行的代碼,我想知道什么是將此選定行復制到DataTable的代碼。
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
try
{
dataGridView1.Rows.RemoveAt(row.Index);
}
catch (Exception)
{
throw;
}
}
}
DataRow row = ((DataRowView)row.DataBoundItem).Row
使用上面的代碼行,您可以讀取每個選定項目的數據表行。
復制
var datarow = ((DataRowView)row.DataBoundItem).Row;
newTable.Rows.Add(datarow.ItemArray);
完整的示例代碼
public partial class Form1 : Form
{
private DataTable table = new DataTable();
private DataTable newTable;
public Form1()
{
InitializeComponent();
table.Columns.AddRange(new DataColumn[] {
new DataColumn("id",typeof(int)),
new DataColumn("Desc",typeof(string))
});
newTable = table.Copy();
dataGridView1.DataSource = table;
dataGridView2.DataSource = newTable;
table.Rows.Add(1, "One");
table.Rows.Add(2, "Two");
table.Rows.Add(3, "Three");
table.Rows.Add(4, "Four");
table.Rows.Add(5, "Five");
}
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
try
{
var datarow = ((DataRowView)row.DataBoundItem).Row;
newTable.Rows.Add(datarow.ItemArray);
dataGridView1.Rows.RemoveAt(row.Index);
}
catch (Exception)
{
throw;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.