使用DataTable的DataGrid获取要显示的动态数据。对数据所做的所有更改都发生在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();
}
}
我需要这样的东西:
DataTable ... = DataGrid.ItemsSource;
答案 0 :(得分:0)
能解决问题吗?
DataTable dt = DataGrid.DataSource as DataTable;
答案 1 :(得分:-1)
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;
}
检查