简体   繁体   中英

Copy the Contents of DataGrid in Wpf to DataTable

I have one dataGrid filled with some values.

I need to copy the contents of dataGrid to dataTable.

After copying the DataTable to Excel sheet, the result was not the expected one. Kinly help in fixing this. The below was the result. 这是结果

     private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        dt = new System.Data.DataTable();
        for (int i = 0; i < dataGrid.Columns.Count; i++)
        {
            dt.Columns.Add();
        }

        System.Data.DataRow dr;
        for (int row = 0; row < dataGrid.Items.Count; row++)
        {
            dr = dt.NewRow();
            for (int col = 0; col < dt.Columns.Count; col++)
            {
                dr[col] = dataGrid.Items[col];
            }
            dt.Rows.Add(dr);
            dt.AcceptChanges();
        }

         //dt = new System.Data.DataTable();
         //dt = (System.Data.DataTable)dataGrid.ItemsSource;
    }

instead of reading from data grid read it from the bound collection

var table = new DataTable();
using(var reader = ObjectReader.Create(data)) 
{
    table.Load(reader);
}

and there you have a data table, for further details you can look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM