2011-02-17 119 views
2

我有兩個DataGridView具有相同的列架構(雖然兩個不同的DataViews作爲DataSource - 如果這很重要)。從一個datagridview移動到另一個datagridview的最佳/最快捷的方式是什麼?如何將行從一個DataGridView移動到另一個DataGridView?

+0

我希望這也是possible.That也是我的問題:)... ListView和列表框可以做那.. – Crimsonland 2011-02-17 23:12:50

+0

我應該指定DataGridView實際上都綁定到DataDable。 DataGridView的重要性在於我想將**選中的行從一個網格移動到另一個網格。查看我的答案,下面是我發現的最快捷的方法 - 如果你有更好的方法,請留言。 – 2011-02-22 19:01:31

回答

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

我相信,如果你在數據表table1的一個排,並希望將其添加到數據表表2,你可以做這樣的事情:

table2.Rows.Add(row.ItemArray); 

,那麼你也必須刪除行是這樣的:

table1.Rows.Delete(row); 

這只是僞代碼,但應該工作,我過去做過。

當然,它只適用於兩個表格具有相同架構的情況,如您所述。

相關問題