Get the DefaultView DataRowView from a DataRow
Asked Answered
T

2

8

Here's the situation: I need to bind a WPF FixedPage against a DataRow. Bindings don't work against DataRows; they work against DataRowViews. I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the DataRow.

What I need is to be able to get a DataRowView for a given DataRow. I can't use the Find() method on the DefaultView because that takes a key, and there is no guarantee the table will have a primary key set.

Does anybody have a suggestion as to the best way to go around this?

Tryptophan answered 28/8, 2008 at 14:45 Comment(0)
D
6

Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table.

        DataRowView newRowView = null;
        foreach (DataRowView tempRowView in myDataTable.DefaultView)
        {
            if (tempRowView.Row == rowToMatch)
                newRowView = tempRowView;
        }
        if (newRow != null)
            UseNewRowView(newRowView);
        else
            HandleRowNotFound();
Dement answered 8/8, 2011 at 23:35 Comment(1)
Hey, it only took me 4-5 years.Tryptophan
T
4
row.Table.DefaultView[row.Table.Rows.IndexOf(row)]

This is an okay answer. But if you find yourself in this situation, you should consider learning more about DataViews and how they are used, then refactor your code to be view-centric rather than table-centric.

Tryptophan answered 28/8, 2008 at 14:52 Comment(2)
This is not a good idea, if the default view has been filtered the indexes may not line up.Dement
@JoelBarsotti: Unless you remove sorts/filters before doing this, after which you can re-add them. But a nice catch. If you have a better answer, please feel free to provide it and (if it works) I'll be happy to select it as better.Tryptophan

© 2022 - 2024 — McMap. All rights reserved.