Search code examples
c#datatableado.netdataview

c# How to build a custom DataView from a DataTable?


I need to create a DataView from a DataTable, but with an unusual twist:

I need to decide (with code) on a row-by-row basis which rows in the DataTable are included in the DataView.

DataTable dt = LoadData();
DataView dv = new DataView(dt);

foreach (DataRow row in dt.Rows)
{
    if (RowIsGood(row))
    { 
        // This obviously doesn't work but I need equivalent logic:
        DataRowView drv = new DataRowView();
        drv.Row = row;
        dv.Add(drv);
    }
}

Some important things to note:

  1. The code in the RowIsGood function above is too complicated to replicate using the standard RowFilter method.
  2. The DataTable has the potential to be very large. It is also referenced by multiple grid controls. Adding temporary columns to the DataTable to facilitate a RowFilter operation is not possible.
  3. I'm using .NET v4.0.

Is then even possible with the DataTable/DataView architecture?

Does LINQ allow me to customize a DataView like I need?


Solution

  • Since you are looking for a row by row solution and already have a function that takes a DataRow and returns a bool.

    Simply add the refernce to System.Data.DataSetExtensions And use the AsDataView Method

    DataView dv=DT.AsEnumerable().Where(RowIsGood).AsDataView();