Sunday, November 10, 2013

How to Sort and Filter in Datatable in C#


// How to Sort and Filter in Datatable          

// Connection Declaration and Fill the Values to Datatable

SqlConnection sqlConnection = new SqlConnection("Data Source=DataSource; Initial Catalog=DBName; User ID=sa; Password=Password;");

sqlConnection.Open();

SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * from Employee", sqlConnection);

DataTable dataTableFill = new DataTable();

dataAdapter.Fill(dataTableFill);

// Sorting

const string sortColumn = "EmpName ASC";

dataTableFill.DefaultView.Sort = sortColumn;

DataTable dtSorting = dataTableFill.DefaultView.ToTable(); 

// Filter

const string filterCondition = "1001";

DataRow[] drRows = dataTableFill.Select("EmpCode = '" + filterCondition + "'");

DataTable dtFilter = drRows.CopyToDataTable();

No comments:

Post a Comment