C# DataGridView Sorting and Filtering
The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. A DataView provides a means to filter and sort data within a DataTable. The following C# program shows how to filter and sort a DataGridView by using a DataView.
How to sort Datagridview
The DataGridView control in C# provides automatic sorting, so that you can manually sort any column in the datagridview control. You can sort the data in ascending or descending order based on the contents of the specified column. Also you can see the DataGridView sorting when user clicks on the column header.
In the above code , datagridview sort the title column thats 1st column.
How to filter Datagridview
You can filter datagridview column in many ways. You can sort data while retrieving it from database using order by clause or you can use the following method.
In the above code, datagridview is filter the column Type and value is Business.
public partial class Form1 : Form
DataSet ds = new DataSet();
private void Form1_Load(object sender, EventArgs e)
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT title_id,title,type,pub_id FROM Titles";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataGridView1.DataSource = ds.Tables;
private void button1_Click(object sender, EventArgs e)
dv = new DataView(ds.Tables, "type = 'business' ", "type Desc", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;
private void button2_Click(object sender, EventArgs e)