如何将行从一个DataGridView移动到另一个DataGridView?

时间:2011-02-17 23:09:58

标签: c# winforms datagridview

我有两个具有相同列模式的DataGridViews(尽管两个不同的DataViews作为DataSource - 如果这很重要)。将行从一个数据网格视图移动到另一个数据网格的最佳/最快方法是什么?

2 个答案:

答案 0 :(得分:1)

我相信如果你在DataTable table1中有一行并希望将它添加到DataTable table2,你可以这样做:

table2.Rows.Add(row.ItemArray);

然后您还必须删除这样的行:

table1.Rows.Delete(row);

这只是伪代码,但应该可行,我过去就是这样做的。

当然,只有当两个表都具有相同的模式时才会起作用,如上所述。

答案 1 :(得分:1)

即使我有两个DataTable作为我的DataGridViews的绑定,我也看不到使用DataGridView获取所选行并移动它们的任何方法,这是我的应用程序的要求。

<强> GridUtility.cs

    /// <summary>
    /// Gets a list of the DataRow objects that are the datasources for a DataGridViews selected rows
    /// </summary>
    /// <param name="rows"></param>
    /// <returns></returns>
    public static DataRow[] GetSelectedDataRows(DataGridView grid)
    {   
        DataRow[] dRows = new DataRow[grid.SelectedRows.Count];
        for (int i = 0; i < grid.SelectedRows.Count; i++)
            dRows[i] = ((DataRowView)grid.SelectedRows[i].DataBoundItem).Row;

        return dRows;  
    }

    /// <summary>
    /// move row from one grid to another
    /// </summary>
    public void MoveRows(DataTable src, DataTable dest, DataRow[] rows)
    {
        foreach (DataRow row in rows)
        {   
            // add to dest
            dest.Rows.Add(row.ItemArray);

            // remove from src
            src.Rows.Remove(row);
        }
    }

使用它:

GridUtility.MoveRows(fromTable, toTable, 
    GridUtility.GetSelectedDataRows(fromDataGridView));
相关问题