简体   繁体   中英

How to programatically fill a dataGrid from DataTable in WPF without using ItemSource

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.

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)]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM