I'm not sure if the ItemsSource data of your DataGrid is a collection of objects or a DataTable.
I used the collection as the ItemsSource of the DataGrid and converted its data to the DataTable through the following code. And by displaying the DataTable in another DataGrid to check whether the data is successfully converted. You could check it and try to refer to it in your project.
The code of xaml:
<StackPanel Orientation="Horizontal">
<DataGrid Name="dg" Width="300" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Birthday" Binding="{Binding Birthday}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<TextBlock Text="{Binding Details}" Margin="10" />
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
<Button Content="convert " Height="50" Click="Button_Click_1" />
<DataGrid x:Name="dg2" Width="400" >
</DataGrid>
</StackPanel>
The code of xaml.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Windows;
namespace DataGridToDataTable
{
public partial class MainWindow : Window
{
DataTable myDataTable;
public MainWindow()
{
InitializeComponent();
List<User> users = new List<User>();
users.Add(new User() { Id = 1, Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new User() { Id = 2, Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new User() { Id = 3, Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });
dg.ItemsSource = users;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var list = new List<User>(dg.ItemsSource as IEnumerable<User>);
myDataTable = ToDataTable(list);
if (myDataTable != null)
{
}
dg2.ItemsSource = myDataTable.DefaultView;
}
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Birthday { get; set; }
public string Details
{
get
{
return String.Format("{0} was born on {1} and this is a long description of the person.", this.Name, this.Birthday.ToLongDateString());
}
}
}
}
The picture of result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.