We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Use DataTable as ItemSource for DataGrid

Hi,

is it possible to use a DataTable as ItemSource for DataGrid?

XAML:
             <grid:SfDataGrid x:Name="dataGrid" AutoGenerateColumns="True"/>

C#:
            DataTable table = new DataTable();
            table.Columns.Add("Column1", typeof(string));
            table.Columns.Add("Column2", typeof(string));
            table.Columns.Add("Column3", typeof(string));
            table.Rows.Add("Entry1", "Entry2", "Entry3");
            table.Rows.Add("Entry4", "Entry5", "Entry6");
            table.Rows.Add("Entry7", "Entry8", "Entry9");
            dataGrid.ItemsSource = table.DefaultView;

this does not work for me.

Best Regards,
Frank

1 Reply

MA Mohanram Anbukkarasu Syncfusion Team December 16, 2019 12:25 PM UTC

Hi Frank,   
  
Thank you for contacting Syncfusion support.

As of now, DataGrid doesn’t have support to bind DataTable to the ItemsSource in UWP platform. Microsoft provided DataTable support only from Fall Creators update but our UWP library was generated by targeting the version as Build:10240 in order to provide backward compatibility for all the UWP versions from initial. Now, we don’t have any immediate plan to upgrade our library to build with the latest SDK version and so unable to provide direct support to bind ItemsSource with DataTable.   
  
You can create your UWP application by specifying the Target and Min version as Fall Creators Update or later versions, so that you can get the DataTable API. And then use the below code to convert DataTable to the ObservableCollection of Dynamic object and bind this collection to the ItemsSource of DataGrid. It will not be required to create Model and this helper method will support you to use it for different columns. Try using the below code example and let us know if this helps you.   
  
Code example:    

public static ObservableCollection<dynamic> ToDynamic(this DataTable dt)   
{   
    var dynamicDt = new ObservableCollection<dynamic>();   
    foreach (System.Data.DataRow row in dt.Rows)   
    {   
        dynamic dyn = new ExpandoObject();   
        dynamicDt.Add(dyn);   
        //Converting the DataTable collcetion in Dynamic collection    
        foreach (System.Data.DataColumn column in dt.Columns)   
        {   
            var dic = (IDictionary<stringobject>)dyn;   
            dic[column.ColumnName] = row[column];   
        }   
    }   
    return dynamicDt;   
}   
   
dataGrid.ItemsSource = ToDynamic(table);   


Please let us know if you require further assistance from us.    
  
Regards,   
Mohanram A.   



Loader.
Live Chat Icon For mobile
Up arrow icon