Monday, 16 February 2015

Filter Data Table in C#.

In general code data binding , most times we need to bind data through data table. In some case we might require to filter data. There are Three different ways you can filter data in data table.

  1. Using For loop. 
  2. Using Data view.
  3. Using Linq query.

Here we will see the demo for last two options.

A. Using data view.

Code Example:

DataTable  dt = GetDataTable(); //Get data in datatable
DataView dv = dt.DefaultView;
dv.RowFilter ="id=10"; // Filter column = filter value
dv.Sort =  "id"; //sort column (Desc for descending order)


repeater1.datasource = dv;
repeater1.databind();

The problem with data view is if the filter column does not match, it will return you the full table instead of null.

Helpful Blog :

B. Using Linq query

Code Example: 


DataTable dtdata = GetDataTable(); //Get data in datatable
                 
                        var data = (from dt in dtdata.AsEnumerable()
                                    where Convert.ToString(dt["id"]) == "10" 
                                    select dt
                                   ).ToList();
                        if (data.Count > 0)
                        {
                            DataTable dtlevel3 = new DataTable();
                            dtlevel3 = data.CopyToDataTable();
                            repeater1.datasource = dv;
                            repeater1.databind();
                        }

For c# code you will require to add namespace : using  System.Linq; 
For Sharepoint you need to add namespace : using Microsoft.SharePoint.Linq;

No comments:

Post a comment