wpf 如何将 DataGrid 转换为 dataTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21827339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:03:43  来源:igfitidea点击:

How to convert DataGrid to dataTable

wpfvb.netwpfdatagridwpf-4.0

提问by NorCode

I want to copy all the datagrid records into datatable without using any loop. For Ex:

我想在不使用任何循环的情况下将所有数据网格记录复制到数据表中。例如:

Dim dt as New DataTable
dt = Datagrid1.Items

But this is not Working and giving an error message.

但这不起作用并给出错误消息。

My Development platform is Visual studio 2010 and language is WPF with vb.net 4.0

我的开发平台是 Visual Studio 2010,语言是带有 vb.net 4.0 的 WPF

回答by Rishap Gandhi

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

这是在不使用 LOOP 的情况下将所有记录从 DATAGRID 传输到 DATATABLE 的方法。

VB:

VB:

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

C#:

C#:

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

回答by Rob Aston

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.

这取决于数据网格的填充方式。如果 DataContext 属性设置为 DataTable,则您只需检索此值并将其转换为 DataTable。

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

没有直接方法可以将其从 DataGrid 元素转换为 DataTable。

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.

如果您想手动执行此操作,则必须创建 DataTable 的一个实例,然后使用循环从 DataGrid 中的项目创建行。

回答by luka

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

要将 dataGrid 转换为带有标题行的数据表,您可以按照以下步骤操作:

1) create the method to retrive the cell

1)创建检索单元格的方法

  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"

2)遍历所有项目并将内容传递给数据表“单元格”

    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;

And here a helper class just to use it.

这里有一个助手类只是为了使用它。

 /// <summary>
/// Class to help to retrive the Data Grid Contain
/// </summary>
public static class DataGridHelper
{
    /// <summary>
    /// Retrive the cell contains
    /// </summary>
    /// <param name="dg">DataGrid</param>
    /// <param name="row">row</param>
    /// <param name="column">column</param>
    /// <returns>DataGrid Cell content</returns>
    static public DataGridCell GetCell(DataGrid dg, int row, int column)
    {
        DataGridRow rowContainer = GetRow(dg, row);

        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

            // try to get the cell but it may possibly be virtualized
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                // now try to bring into view and retreive the cell
                dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }
    /// <summary>
    /// Get row content
    /// </summary>
    /// <param name="dg">Datagrid</param>
    /// <param name="index">Index</param>
    /// <returns>DataGridRow</returns>
    static public DataGridRow GetRow(DataGrid dg, int index)
    {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            // may be virtualized, bring into view and try again
            dg.ScrollIntoView(dg.Items[index]);
            row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }
    static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }
}

回答by Nocturnal

i just tested this and this works

我刚刚测试了这个,这有效

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

回答by J R B

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

您必须在 DataGrid 上循环并将项目添加到 Datatable。下面的链接可能会有所帮助。

DataGridView selected rows to DataTable

DataGridView 选择的行到 DataTable