How Can Convert DataRow to DataRowView in c#
Asked Answered
T

4

13

Can or how to convert DataRow to DataRowView?

For example:

   DataTable dt=ds.Tables[0];
   DataRow dr= dt.NewRow();           
   DataRowView drv = ???? 
Torrietorrin answered 26/3, 2013 at 7:58 Comment(0)
H
29

Use

DataTable dt=ds.Tables[0];
DataRow dr= dt.NewRow();         
DataRowView drv= dt.DefaultView[dt.Rows.IndexOf(dr)];
Hanford answered 26/3, 2013 at 8:2 Comment(1)
You must remember that if the default view has been filtered the indexes may not line up. Similar solution https://mcmap.net/q/903636/-get-the-defaultview-datarowview-from-a-datarowBrickle
L
2

The above method does not work if the DataRow status is Detached. This code snippet could be used in such case:

        DataRow dRow = dataTable.NewRow();
        //...
        DataRowView dRowView = dRow.Table.DefaultView.AddNew();

        for (int i = 0; i < dRow.ItemArray.Length; i++)
        {
            dRowView.Row[i] = dRow[i];
        }
Linnie answered 5/6, 2014 at 16:36 Comment(1)
dear @Subramani, Thank you for your help, and please if this question is useful set up voteTorrietorrin
B
2
DataRowView selecRow = dataTable.DefaultView.Cast<DataRowView>().FirstOrDefault(a => a.Row == desRow);

works, this is a litte shorter without "where" ;-)

Byran answered 11/4, 2018 at 16:10 Comment(0)
T
1

Use. It also works if the DataGrid is ordered.

DataRowView selecRow = dataTable.DefaultView.Cast<DataRowView>().Where(a => a.Row == desRow).FirstOrDefault();
Trever answered 6/2, 2018 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.