2016-05-29 470 views
0

嗨,我正在跟着這個guide以瞭解使用DataGrid。WPF如何把DataGrid轉換成DataTable?

我遇到的問題是如何將數據從DataGrid轉換爲DataTable?

我想獲得工作的代碼是:

DataTable dt = ((DataView)dg.ItemsSource).ToTable(); 

,但它給了我一個錯誤,指出:

無法轉換 類型的對象System.Collections.Generic.List `1 [WPFProject.Person]'鍵入 'System.Data.DataView'。

我的代碼和這個例子非常相似,除了我使用類Person而不是用戶,並且我創建了一個Person類型的列表以便將數據插入到數據網格中。

public class Person 
    { 
     public bool CheckBox { get; set; } 
     public int ID { get; set; } 
     public string Name { get; set; } 
    } 

謝謝。

回答

1

你不能這樣轉換它。只有在DataGridItemSource不是DataView時,您的密碼纔有效。您需要明確編寫代碼(您可以輕鬆地谷歌任何collection<T>DataTable)將您的collection轉換爲DataTable。看看下面的例子:

XAML

<StackPanel> 
    <DataGrid ItemsSource="{Binding list}" x:Name="myGrid"/> 
    <Button Content="convert back" Click="Button_Click_1" /> 
</StackPanel> 

邏輯:

private void Button_Click_1(object sender, RoutedEventArgs e) 
    { 
     var list = new List<MyClass>(myGrid.ItemsSource as IEnumerable<MyClass>); 
     var dataTable = ToDataTable(list); 
     if (dataTable != null) 
     { 

     } 
    } 

    public static DataTable ToDataTable<T>(List<T> items) 
    { 
     DataTable dataTable = new DataTable(typeof(T).Name); 

     //Get all the properties 
     PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 
     foreach (PropertyInfo prop in Props) 
     { 
      //Setting column names as Property names 
      dataTable.Columns.Add(prop.Name); 
     } 
     foreach (T item in items) 
     { 
      var values = new object[Props.Length]; 
      for (int i = 0; i < Props.Length; i++) 
      { 
       //inserting property values to datatable rows 
       values[i] = Props[i].GetValue(item, null); 
      } 
      dataTable.Rows.Add(values); 
     } 
     //put a breakpoint here and check datatable 
     return dataTable; 
    } 

輸出

Grid

DataTable

0

你不能在WPF中像winforms那樣做。在Wpf中,您可以像這樣從dataTable中設置datagrid ItemsSource。

dg.ItemsSource = dataTable.AsDataView(); 

你的情況,你想獲得的dataTableDataGrid中。 所以你可以試試下面的代碼。

DataView view = (DataView) dg.ItemsSource; 
DataTable dataTable = view.Table.Clone(); 
foreach (var dataRowView in view) 
{ 
    dataTable.ImportRow(dataRowView.Row); 
} 
var dataTableFromDataGrid = dataTable;