如何在C#中将所选行从DataGridView复制到DataTable

时间:2018-10-22 07:41:02

标签: c# .net datagridview datatable ado.net

我有一个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;
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

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;
            }
        }
    }
}
相关问题