Convert and use DataTable in WPF DataGrid?

后端 未结 3 749
臣服心动
臣服心动 2020-12-09 19:46

In normal WinForm application you can do that:

DataTable dataTable = new DataTable();
dataTable = dataGridRecords.DataSource;

but how to do

相关标签:
3条回答
  • 2020-12-09 20:26

    In WPF you don't do this

    DataGrid.ItemsSource = DataTable;
    

    Instead you do

     DataGrid.ItemsSource = DataTable.AsDataView();
    

    In order to get DataTable back you can do something like this

    public static DataTable DataViewAsDataTable(DataView dv)
    {
        DataTable dt = dv.Table.Clone();
        foreach (DataRowView drv in dv)
           dt.ImportRow(drv.Row);
        return dt;
    }
    
    DataView view = (DataView) dataGrid.ItemsSource;
    DataTable table = DataViewAsDataTable(view)
    
    0 讨论(0)
  • 2020-12-09 20:30

    try this

        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();
            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;
    
        }
    
    0 讨论(0)
  • 2020-12-09 20:32

    You don't need the DataViewAsDataTable method. Just do the following:

    DataTable dt = ((DataView)dataGrid1.ItemsSource).ToTable();

    0 讨论(0)
提交回复
热议问题