c# - 如何从 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;
解决方案
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;
}
检查这个
推荐阅读
- spring-boot - ResourceServerTokenServicesConfiguration 中的 userInfoRestTemplateFactory 需要单个 bean,但找到了 4 个
- django - 检查用户是否具有列表权限并将结果转换为字典的有效方法
- java - 即使映射看起来正确,休眠映射异常
- docker - 在 docker compose 文件中设置 .env 变量时遇到问题
- django - 根据每个 DevicePart 模型计算 django 模型设备中的总数,包括数量
- django - 如果已经在 django 中使用任何社交身份验证登录,如何从登录页面重定向登录用户?
- awk - 如何执行将环境变量和变量参数从带有 xargs 的文件中合并的命令?
- production - Laravel Telescope 没有与 Laravel Voyager 一起工作。如何在 Laravel 7 中保护 /telescope/* 路线?
- django - 如何在 django 中创建下载视图
- javascript - 字符串中的 newDate() 在 Chrome 和 Safari 中创建不同的结果