Thursday, January 27, 2011

Filter DataTable

Most of them we come across the situation where we need to filter the data from Datatable. Below are the two ways we can achieve this functionality.

1. Filter the Datatable and save the result in Datarow

SqlConnection myConn = new SqlConnection(strConString);
string strSql = "select * from Employee";DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strSql, myConn);

// Filters the data by "EmployeeID = 143" and returns an array of DataRow
da.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow[] dRow = dt.Select("EmployeeID=’143’");
for (int i = 0; i < dRow.Length; i++)
{
Response.Write("Row " + dRow[i]["Employee_Name"].ToString());
}

2. Create DataView populate it with Datatable and then use Filter Property of Dataview

DataView dtView = ds.Tables["Employee"].DefaultView;
dtView.RowFilter = "EmpployeeID = '143'";

No comments:

Post a Comment