【问题标题】:Importing a DataRowView Object to DataTable with ImportRow() Displays Empty Row?使用 ImportRow() 将 DataRowView 对象导入 DataTable 显示空行?
【发布时间】:2019-07-12 17:27:13
【问题描述】:

我正在尝试将所选项目从我的DataGrid 转移到我的DataTable,我将使用它与另一个DataGrid 绑定。我将一行导入DataTable,如下:

DataRowView row = (DataRowView)firstDataGrid.SelectedItems[0]; //Picking the first one as an example
myDataTable.ImportRow(row.Row);

我的DataTable 与我的另一个DataGrid 绑定如下:

<DataGrid x:name="secondDataGrid" ItemsSource="{Binding myDataTable}"> //This is not the same data grid from above

我有一个按钮,它绑定到执行第一块代码的命令,如下所示:

<ButtonCommand="{Binding DoFirstChunkOfCodeCommand}" CommandParameter="{Binding ElementName=firstDataGrid}"></Button>

但是,当我对其进行测试时,它最终只在我的第二个 DataGrid 中添加了空行,我已通过以下方式确认 row.Row 不为空:

MessageBox.Show(row.Row["SomeColumn"].ToString());

最终打开一个包含正确值的消息框。那么,当行不为空时,为什么会在我的 dataGrid 中添加一个空行?

【问题讨论】:

    标签: c# wpf datatable datagrid


    【解决方案1】:

    事实证明,在导入行之前,我必须先将列添加到我的DataTable,如下所示:

    DataColumn column;
    
    //Repeat this chunk for each column, changing DataType and ColumnName as neccessary
    column = new DataColumn();
    column.DataType = Type.GetType("System.String");
    column.ColumnName = "col1";
    myDataTable.Columns.Add(column);
    

    这使得 ImportRow() 方法按预期运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 2011-08-14
      相关资源
      最近更新 更多