SiteMap  | About    

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.

datgridview filter sort in c#

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.

dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
how to datgridview sort in c#

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.

DataView dv; dv = new DataView(ds.Tables[0], "type = 'business' ", "type Desc", DataViewRowState.CurrentRows); dataGridView1.DataSource = dv;
how to datgridview filter in c#

In the above code, datagridview is filter the column Type and value is Business.

using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        DataSet ds = new DataSet();

        public Form1()

        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);
            dataadapter.Fill(ds, "Titles_table");

            dataGridView1.DataSource = ds.Tables[0];


        private void button1_Click(object sender, EventArgs e)
            DataView dv;
            dv = new DataView(ds.Tables[0], "type = 'business' ", "type Desc", DataViewRowState.CurrentRows);
            dataGridView1.DataSource = dv;

        private void button2_Click(object sender, EventArgs e)
            dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
} (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.