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?

Thanks in advance!

3

2 Answers

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();
0
DataView dv = (from n in DT.AsEnumerable() Where RowIsGood(n) select n ).AsDataView();
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest