How to get the index of a DataRowView (correctly)?

156 views Asked by At

I am using this Method to obtain the index of a DataRowView:

public static int GetIndex(this DataRowView rowView)
{
    for (int i = 0; i < rowView.DataView.Count; i++)
    {
        if (rowView.DataView[i] == rowView)
            return i;
    }

    return -1;
}

Now I have a use case with a regular given RowView that returns -1. The rowView.DataView contains exactly the same rowView, but rowView.DataView[i] == rowView still returns false.

So why are there cases where this comparison returns an incorrect result, and what are those cases?

And how can I prevent this and get the index of a DataRowView correctly?

1

There are 1 answers

0
Karen Payne On

You can get the row index from .Row property of a DataRowView.

using System.Data;
using System.Reflection;

. . .

public static class Extensions
{
    public static int RowId(this DataRow row)
    {
        FieldInfo fieldInfo = row.GetType().GetField("_rowID",
            BindingFlags.NonPublic | BindingFlags.Instance);
        return Convert.ToInt32(fieldInfo!.GetValue(row));
    }
}

Example, table is a DataTable.

DataView view = table.DefaultView;
foreach (DataRowView rowView in view)
{
    Debug.WriteLine($"{rowView.Row.RowId()}");
}