The below code snippet shows how to filter data in a data table based on certain values.
///
/// Filters the Data Table based on the Employee ID and returns the No. of
Row Count available.
///
///
///
private void button1_Click(object sender, EventArgs e)
{
DataTable dtTestTable = new DataTable();
DataRow drRow;
//Validating the Table
if (dtTestTable != null & dtTestTable.Columns.Count > 0)
{
dtTestTable.Rows.Clear();
dtTestTable.Columns.Clear();
}
//creating columns
dtTestTable.Columns.Add("EmployeeID", typeof(System.Int16));
dtTestTable.Columns.Add("FirstName", typeof(System.String));
dtTestTable.Columns.Add("LastName", typeof(System.String));
//Adding Rows
for (int rowCount = 1; rowCount <= 10; rowCount++)
{
drRow = dtTestTable.NewRow();
drRow["EmployeeID"] = rowCount;
drRow["FirstName"] = "First Name of Row " + rowCount;
drRow["LastName"] = "First Name of Row " + rowCount;
dtTestTable.Rows.Add(drRow);
}
//display Total Records Count message
MessageBox.Show(dtTestTable.Rows.Count.ToString ());
//filter data table rows based on the employee ID;
Int16 empID=9;
//Set the filter condition and assign to RowFilter
dtTestTable.DefaultView.RowFilter = "EmployeeID=" + empID;
//display the filtered record count
MessageBox.Show(dtTestTable.DefaultView.ToTable().Rows.Count.ToString ());
}
Happy Learning !!!