Search code examples
wpfdatatablecastingdatagrid

WPF How to convert from DataGrid to DataTable?


Hi I am following along with this guide in order to learn about using DataGrid.

The problem I am running into is how do I convert the data from the DataGrid into a DataTable?

The code I am trying to get working is:

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

but it gives me an error stating:

Unable to cast object of type 'System.Collections.Generic.List`1[WPFProject.Person]' to type 'System.Data.DataView'.

My code is very much similar to the example except I use the class Person instead of user and I create a list of type Person in order to insert data into the datagrid.

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

Thank you.


Solution

  • You can't convert it that way. Your code will only work if the ItemSource of your DataGrid is not a DataView. You need to write code explicitly (which you can easily google any collection<T> to DataTable) to convert your collection into DataTable. have a look at below example:

    XAML

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

    Logic:

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

    Output

    Grid

    DataTable