I am trying to transfer a selected item from my DataGrid
to my DataTable
that I will use to bind with another DataGrid
. I import a row to the DataTable
as follows:
DataRowView row = (DataRowView)firstDataGrid.SelectedItems[0]; //Picking the first one as an example
myDataTable.ImportRow(row.Row);
My DataTable
has my other DataGrid
binding to it as follows:
<DataGrid x:name="secondDataGrid" ItemsSource="{Binding myDataTable}"> //This is not the same data grid from above
I have a button that binds to a command that executes the first chunk of code as follows:
<ButtonCommand="{Binding DoFirstChunkOfCodeCommand}" CommandParameter="{Binding ElementName=firstDataGrid}"></Button>
However, when I test it out, it ends up adding only empty rows to my second DataGrid
, I have confirmed that row.Row
is NOT null by the following:
MessageBox.Show(row.Row["SomeColumn"].ToString());
Which ended up opening a message box containing the correct value. So, why then is an empty row being added to my dataGrid when the row is not null?
It turns out I have to add the columns to my DataTable
first before importing rows as follows:
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);
This makes the ImportRow() method function as expected to.