简体   繁体   中英

wpf datagrid Ienumerable returning null

Using C#.NET4.5, MS Visual Studio 2012, WPF.

Hi guys got some code here that giving me null. This code was a previous solution that I tried. I received no errors but never tested through it since today when I found I debugged there rows were null.

Heres the code:

1st I throw my data I collected from SQL to a datatable and threw it into my datagrid...

 private void LoadPareto(string pg)
 {
     DataTable tbl = new DataTable();
     tbl = mysqlq.SQL_GetPareto(pg);
     paretogrid.ItemsSource = tbl.AsDataView();
     // InsertColumns();
     ShowArrows();
 }

2nd set up binding in XAML...

<DataGrid Name ="paretogrid" ItemsSource="{Binding}"

3rd I created an Ienumerable...

public IEnumerable<System.Windows.Controls.DataGridRow> GetDataGridRow(System.Windows.Controls.DataGrid grid)
{
    var itemsource = grid.ItemsSource as System.Collections.IEnumerable;
    if (null == itemsource) yield return null;
    foreach (var item in itemsource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow; // null?
        if (null != row) yield return row;
    }
}

Then I call it in this method...

private void ShowArrows()
{
    var rows = GetDataGridRow(paretogrid); // fetching null?

    foreach (DataGridRow r in rows)
    {
        DataRowView rv = (DataRowView)r.Item;
        foreach (DataGridColumn column in paretogrid.Columns)
        {
            if (column.GetCellContent(r) is TextBlock)
            {
                TextBlock cellcontent = column.GetCellContent(r) as TextBlock;
                MessageBox.Show(cellcontent.Text);
            }
        }
    }
}

Now the Problem I have is in the Ienumerbale I see my item source contains 12007 records which is perfect. Yet when I step through I find ...

var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;

Is returning null which my "if" statement find it as a false so skips the yield. So of course, when i go to step through the foreach loop in "showarrows" method It doesnt bother since there's null.

So where am I going wrong? am I missing something?

Thanks in advance guys n girls!

Your DataGrid has't yet updated when you're getting the rows. A solution would be to paretogrid.UpdateLayout() right after you set the ItemsSource .

Note, that this is not really good to mix the data and UI code. What you're trying to do could've probably been done in XAML, and you wouldn't have this problem.

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