首页 > 解决方案 > 如何从 DataGrid 中复制所有数据并粘贴到 DataTable 中?(C#/WPF)

问题描述

DataGrid 使用 DataTable 获取要显示的动态数据。对数据所做的所有更改都发生在 DataGrid 中(更改列名、删除列、更改列顺序等)。要上传转换后的数据,您需要使用 DataTable ...

由于所有更改都发生在 DataGrid 中,因此它们在 DataTable 中没有更改。如何从 DataGrid 复制所有更改的数据并粘贴到 DataTable 中?

// For example: Changing column names
DataGridColumn columnHeader = CsvGrid.CurrentColumn;
if (columnHeader != null)
{
    string input = new InputBox(columnHeader.Header.ToString()).ShowDialog();
    if (!string.IsNullOrEmpty(input))
    {
        _csvTable.Columns[columnHeader.Header.ToString()].ColumnName = input;
        columnHeader.Header = input;
        GetChecksBox();
     }
}

我需要这样的东西:

数据表 ... = DataGrid.ItemsSource;

标签: c#wpfdatagrid

解决方案


public static DataTable DataGridtoDataTable(DataGrid dg)
    {


        dg.SelectAllCells();
        dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
        ApplicationCommands.Copy.Execute(null, dg);
        dg.UnselectAllCells();
        String result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
        string[] Lines = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
        string[] Fields;
        Fields = Lines[0].Split(new char[] { ',' });
        int Cols = Fields.GetLength(0);
        DataTable dt = new DataTable();
        //1st row must be column names; force lower case to ensure matching later on.
        for (int i = 0; i < Cols; i++)
            dt.Columns.Add(Fields[i].ToUpper(), typeof(string));
        DataRow Row;
        for (int i = 1; i < Lines.GetLength(0)-1; i++)
        {
            Fields = Lines[i].Split(new char[] { ',' });
            Row = dt.NewRow();
            for (int f = 0; f < Cols; f++)
            {
                Row[f] = Fields[f];
            }
            dt.Rows.Add(Row);
        }
        return dt;

    }

检查这个


推荐阅读