filter datatable in asp.net (datatable.select)

Some times we need to filter records in DataTable.

For this we have select() methord.which is used with DataTable and always returns the array.

so lets begin..

For showing Result we used GridView.

.aspx page
[scourcecode language=”csharp”]

Untitled Page

[/scourcecode]
.cs page
[scourcecode language=”csharp”]
using System;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//create DataTable
DataTable dt = new DataTable();
//Add Tow Columns in DataTable
dt.Columns.Add(“EmpCode”,typeof(int));
dt.Columns.Add(“EmpName”,typeof(string));
//Add Tow Rows
dt.Rows.Add(101, “Ashish”);
dt.Rows.Add(102, “Dynamic”);
//Filter String– we want show data which having EmpCode = 102
string filteringquery = “EmpCode=’102′”;
//Select always return array,thats why we store it into array of Datarow
DataRow[] dr = dt.Select(filteringquery);
//create new table
DataTable dtNew = new DataTable();
//create a clone of datatable dt and store it into new datatable
dtNew = dt.Clone();
//fetching all filtered rows add add into new datatable
foreach (DataRow drNew in dr)
{
dtNew.ImportRow(drNew);
}
//Bind gridview with new datatable for showing the output
gridview1.DataSource = dtNew;
gridview1.DataBind();
}
}
[/scourcecode]

Advertisements
This entry was posted in Asp.Net. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s