How to convert DataGrid to dataTable

笑着哭i 提交于 2019-11-28 13:30:47
Rishap Gandhi

This is the way to transfer all the records from DATAGRID to DATATABLE without using the LOOP.

VB:

Dim dt As New DataTable
dt = CType(DataGrid1.ItemsSource, DataView).ToTable

C#:

DataTable dt = new DataTable();
dt = ((DataView)DataGrid1.ItemsSource).ToTable();  

It depends how the datagrid is populated. If the DataContext property is set to a DataTable then you can simply just retrieve this value and cast to a DataTable.

There is no direct method to convert this to a DataTable from the DataGrid element.

If you wanted to do this manually, you would have to create an instance of the DataTable, then create the rows from the Items in the DataGrid using a loop.

To convert your dataGrid into data table whith header row you can follow this steps:

1) create the method to retrive the cell

  static public DataGridCell GetCell(DataGrid dg, int row, int column)
    {
        DataGridRow rowContainer = GetRow(dg, row);

        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

2) Iterate through all items and pass the content to dada table "cell"

    private void DataGridToDataTable()
    {
        DataTable dt = new DataTable();
        var j = byte.MinValue;//header row handler
        dt.Rows.Add();
        foreach (DataGridColumn column in dataGrid1.Columns)
        {                
            dt.Columns.Add(column.GetValue(NameProperty).ToString());
            dt.Rows[byte.MinValue][j++] = column.Header;
        }

        //data rows handler
        for (int i = byte.MinValue ; i < dataGrid1.Items.Count; i++)
        {
            dt.Rows.Add();
            for (j = Byte.MinValue; j < dataGrid1.Columns.Count; j++)
            {
                DataGridCell dgc = GetCell(dataGrid1, i, j);
                dt.Rows[i + 1][j] =  ((dgc.Content) as TextBlock).Text;
            }
        }
    }  

Keep in mind to use this methods you must will reference this using:

using System.Windows.Media;
using System.Data;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

i just tested this and this works

Dim dt as New DataTable
dt = ctype(Datagrid1.Datasource, DataTable)
J R B

You have to loop on DataGrid and add item to Datatable. below link may help.

DataGridView selected rows to DataTable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!