-1

I have a DataTable filled with Data from an SQL server.

I am trying to copy the DataTable to a DataGrid without using ItemsSource Currently I can copy the Columns over using a loop..

Private Pages.PageGainLoss gridCreator(DataTable dt)
{
    var DT = dt;
    Pages.PageGainLoss gainLoss = new Pages.PageGainLoss();

    foreach(DataColumn dC in DT.Columns) 
    {
        var col = new DataGridTextColumn();
        col.Header = dC.ColumnName;
        gainLoss.dataGrid.Columns.Add(col);
    }

    foreach(DataRow dR in DT.Rows)
    {
        gainLoss.DataGrid.Items.Add(dR)
    }

    return gainLoss;
}

But I can't seem to figure out the loop to copy over the rows. It copies empty rows to my datagrid.

EXTRA: The reason I am using this approach is because I am using a class to create a Page, which contains a DataGrid and populating the DataGrid before showing it in a frame on Main page. But when I use gainLoss.dataGrid.ItemsSource = dt.DefaultValue; I can't modify the DataGrid or change it's properties such as column width or color because it says the column doesnt exist.

mm8
  • 163,881
  • 10
  • 57
  • 88
Adas
  • 404
  • 2
  • 19
  • 1
    As soon as you say "without using ItemSource" the answer is "you are doing this wrong". What you should be doing to asking questions about the issues you're facing when you do use ItemSource, not trying to circumvent it altogether. – Mark Feldman Nov 06 '18 at 21:12
  • @MarkFeldman Thank you. Any direction you could point me to? – Adas Nov 06 '18 at 21:23
  • 1
    Anything on MVVM, [this answer from the past](https://stackoverflow.com/a/2034333/1177147) is a good starting point. [Josh Smith's article on MVVM](https://msdn.microsoft.com/en-us/magazine/dd419663.aspx) is particularly good and has been the starting point for many, myself included. – Mark Feldman Nov 06 '18 at 22:16

1 Answers1

1

You need to set the Binding property of the DataGridTextColumn:

foreach (DataColumn dC in DT.Columns)
{
    var col = new DataGridTextColumn();
    col.Header = dC.ColumnName;
    col.Binding = new Binding(dC.ColumnName); //<--
    gainLoss.dataGrid.Columns.Add(col);
}

You should also add DataRowViews to the DataGrid:

foreach (DataRow dR in DT.Rows)
{
    dataGrid.Items.Add(DT.DefaultView[DT.Rows.IndexOf(dR)]);
}
mm8
  • 163,881
  • 10
  • 57
  • 88