2014-02-17 38 views
7

我想將所有datagrid記錄複製到datatable中而不使用任何循環。 對於防爆:如何將DataGrid轉換爲dataTable

Dim dt as New DataTable 
dt = Datagrid1.Items 

但這不是工作,並給了一個錯誤消息。

我的開發平臺是Visual Studio 2010和語言是WPF與vb.net 4.0

回答

13

這是所有記錄從DATAGRID轉移到DATATABLE不使用LOOP的方式。

VB:

Dim dt As New DataTable 
dt = CType(DataGrid1.ItemsSource, DataView).ToTable 

C#:

DataTable dt = new DataTable(); 
dt = ((DataView)DataGrid1.ItemsSource).ToTable(); 
+2

我m沒有在C#datagrid上找到「ItemSource」 –

+0

非常感謝 – Sonja

5

這取決於數據網格的填充方式。如果DataContext屬性設置爲DataTable,那麼您可以簡單地檢索該值並將其轉換爲DataTable。

沒有直接的方法將它從DataGrid元素轉換爲DataTable。

如果您想手動執行此操作,您必須創建DataTable的實例,然後使用循環從DataGrid中的Items中創建行。

0

我只是測試這一點,這個工程

Dim dt as New DataTable 
dt = ctype(Datagrid1.Datasource, DataTable) 
1

爲您的數據網格轉換成蒙山頭行的數據表,你可以按照這個步驟:

1)創建方法來檢索單元格

static public DataGridCell GetCell(DataGrid dg, int row, int column) 
    { 
     DataGridRow rowContainer = GetRow(dg, row); 

     if (rowContainer != null) 
     { 
      DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); 
      DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 
      if (cell == null) 
      { 
       dg.ScrollIntoView(rowContainer, dg.Columns[column]); 
       cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 
      } 
      return cell; 
     } 
     return null; 
    } 

2)通過全項修改並通過內容達達表「細胞」

private void DataGridToDataTable() 
    { 
     DataTable dt = new DataTable(); 
     var j = byte.MinValue;//header row handler 
     dt.Rows.Add(); 
     foreach (DataGridColumn column in dataGrid1.Columns) 
     {     
      dt.Columns.Add(column.GetValue(NameProperty).ToString()); 
      dt.Rows[byte.MinValue][j++] = column.Header; 
     } 

     //data rows handler 
     for (int i = byte.MinValue ; i < dataGrid1.Items.Count; i++) 
     { 
      dt.Rows.Add(); 
      for (j = Byte.MinValue; j < dataGrid1.Columns.Count; j++) 
      { 
       DataGridCell dgc = GetCell(dataGrid1, i, j); 
       dt.Rows[i + 1][j] = ((dgc.Content) as TextBlock).Text; 
      } 
     } 
    } 

記住使用這個方法,你必須將引用這個使用:

using System.Windows.Media; 
using System.Data; 
using System.Windows.Controls; 
using System.Windows.Controls.Primitives; 
+0

我得到了這個工作很好,但我不得不添加我自己的GetVisualChild和GetRow方法,因爲它們不在這裏發佈。 – AndrewBenjamin

+0

抱歉忘記了,但正如您看到的,您可以輕鬆創建自己的方法來檢索行和GetVisulaChild。 讓我知道如果你想要我也發佈這種方法 – luka