如何从WPF datagrid获取数据到datatable [英] How to get data from WPF datagrid to datatable

查看:198
本文介绍了如何从WPF datagrid获取数据到datatable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在将代码从Windows窗体迁移到WPF。



在windows中表格代码是:

Datatable dt = datagrid1.Datasource as DataTable



任何人都可以帮助我将它迁移到WPF中。

我试过用

Datatable dt = datagrid1.ItemsSource as DataTable



但是我得到了dt = null

Hi,

I am migrating the code from windows forms to WPF.

in windows forms the code is:
Datatable dt= datagrid1.Datasource as DataTable

Can anyone help me what will it migrate to in WPF.
I tried with
Datatable dt= datagrid1.ItemsSource as DataTable

But I am getting dt=null

推荐答案

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;
            
        }







查看此




check this


你分配给datagrid1.ItemsSource的东西,你得到同样的东西。



如果你不确定你得到什么回来然后分配给一个var对象并检查类型



what you are assigned to datagrid1.ItemsSource, you get the same thing back.

if you are not sure what you are getting back then assign it to a "var" object and check the type

var abc = datagrid1.ItemsSource;

if(abc!=null)
{
 MessageBox.Show(abc.GetType().Name);
}


这篇关于如何从WPF datagrid获取数据到datatable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆