13

Can or how to convert DataRow to DataRowView?

For example:

   DataTable dt=ds.Tables[0];
   DataRow dr= dt.NewRow();           
   DataRowView drv = ???? 
BizApps
  • 6,048
  • 9
  • 40
  • 62
Harry Sarshogh
  • 2,137
  • 3
  • 25
  • 48

4 Answers4

28

Use

DataTable dt=ds.Tables[0];
DataRow dr= dt.NewRow();         
DataRowView drv= dt.DefaultView[dt.Rows.IndexOf(dr)];
J. Steen
  • 15,470
  • 15
  • 56
  • 63
BizApps
  • 6,048
  • 9
  • 40
  • 62
  • 1
    You must remember that if the default view has been filtered the indexes may not line up. Similar solution http://stackoverflow.com/a/6989851/2122718 – marbel82 Apr 23 '15 at 13:09
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];
        }
Subramani
  • 21
  • 1
2
DataRowView selecRow = dataTable.DefaultView.Cast<DataRowView>().FirstOrDefault(a => a.Row == desRow);

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

omei
  • 51
  • 4
1

Use. It also works if the DataGrid is ordered.

DataRowView selecRow = dataTable.DefaultView.Cast<DataRowView>().Where(a => a.Row == desRow).FirstOrDefault();