开发者

How do I move row from one DataGridView to another DataGridView?

I have two DataGridViews that have the same column schema (although two different DataViews as DataSource 开发者_如何学编程- if that matters). What is the best/quickest way to move a row from one datagridview to the other?


I believe if you have a row in DataTable table1 and want to add it to DataTable table2 you could do something like this:

table2.Rows.Add(row.ItemArray);

then you have to also remove the row like this:

table1.Rows.Delete(row);

this is just pseudo code but should work, I did this in the past.

of course it only works if both tables have same schema, as you mentioned.


Even though I have two DataTable as binding for my DataGridViews, I couldn't see any way around using the DataGridView to get the selected rows and move them, which is a requirement for my application.

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);
        }
    }

To use it:

GridUtility.MoveRows(fromTable, toTable, 
    GridUtility.GetSelectedDataRows(fromDataGridView));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜