Csharp/C#教程:在WPF DataGrid中转换并使用DataTable?分享


在WPF DataGrid中转换并使用DataTable?

在正常的WinForm应用程序中,您可以这样做:

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

但是如何使用WPF数据网格呢?

 dataTable = dataGridRecords.ItemsSource; 

也不会工作。

在WPF中,你不这样做

 DataGrid.ItemsSource = DataTable; 

相反,你做

  DataGrid.ItemsSource = DataTable.AsDataView(); 

为了获得DataTable,你可以做这样的事情

 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) 

您不需要DataViewAsDataTable方法。 只需执行以下操作:

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

试试这个

上述就是C#学习教程:在WPF DataGrid中转换并使用DataTable?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  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[] { "rn", "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; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/989138.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐