In C#, when working with DataTable objects, you often need to filter data dynamically without modifying the original table. The DataView class is designed for this purpose. It provides a view of a DataTable and allows you to sort, filter, and search rows efficiently.
Understanding the Scenario
Consider you have a DataTable called dt containing columns like:
Symbol
Category
opendatetime
closedatetime
FloorPrice
CeilingPrice
asbanonasba
You want to filter rows where a specific column matches a value.
Using DataView to Filter Rows
else
{
// Create a DataView from the DataTable
DataView dv = dt.DefaultView;
// Apply a filter condition
dv.RowFilter = "asbanonasba = '1'";
// Convert the filtered view back to a DataTable
DataTable dts = dv.ToTable();
}
Step-by-Step Explanation
Create a DataView
DataView dv = dt.DefaultView;
Set the RowFilter
dv.RowFilter = "asbanonasba = '1'";
"ColumnName operator value"
dv.RowFilter = "Category = 'IND'"; // Filter by text
dv.RowFilter = "FloorPrice > 100"; // Filter numeric values
dv.RowFilter = "opendatetime >= '2025-10-01'"; // Filter dates
Convert the Filtered View Back to a DataTable
DataTable dts = dv.ToTable();
dv.ToTable() creates a new DataTable containing only the rows that satisfy the RowFilter.
You can now use dts for binding to UI controls, exporting, or further processing.
Optional: Selecting Specific Columns and Distinct Rows
You can also select only certain columns or remove duplicates using the overloaded ToTable method:
DataTable distinctTable = dv.ToTable(
true, // distinct rows only
"Symbol", "Category", "FloorPrice" // columns to include
);
Practical Example
Suppose your DataTable has the following data:
| Symbol | Category | asbanonasba |
|---|
| ABC | IND | 1 |
| DEF | IND | 0 |
| XYZ | FMCG | 1 |
Filtering with
dv.RowFilter = "asbanonasba = '1'";
The resulting DataTable will contain:
| Symbol | Category | asbanonasba |
|---|
| ABC | IND | 1 |
| XYZ | FMCG | 1 |
Tips and Best Practices
Always check for column names in the filter string — typos will throw exceptions.
String values must be enclosed in single quotes ' '.
DateTime values must be in MM/dd/yyyy format or use # in US format:
dv.RowFilter = "opendatetime >= #10/01/2025#";
For numeric columns, quotes are not needed:
dv.RowFilter = "CeilingPrice >= 500";
DataView vs LINQ: DataView is faster for UI-bound tables; LINQ to DataSet is more flexible for complex queries.
Conclusion
Using DataView and its RowFilter property is a simple and effective way to filter rows in a DataTable without modifying the original data. It’s particularly useful for binding filtered data to grids, reports, or exporting results.