ARTICLE

Windows Form Application DataGridView Operations

Posted by Amit Choudhary Articles | Windows Forms C# March 04, 2011
Implementing simple sorting (Ascending/Descending) for a DataGridView Column.
Reader Level:
Download Files:
 


Implementing simple sorting (Ascending/Descending) for a DataGridView Column.

The DataGridView does not provide any internal funtionality for sorting a column by clicking on the header. So here is a simple example to implement it.
Create a WindowsFormApplication in Visual Studio. Add a new form and add a DataGridView to it.

Now apply the following code to the Form1.cs.

public partial class Form1 : Form
    {
       
int cntr = 0; //used for custom sort toggle
        DataTable dt; // used as datasource of DataGridView
        /// <summary>
        /// Form1 Constructor that calls the intialize component and other custom initalization code
        /// </summary>
        public Form1()
        {
            InitializeComponent();
           
//
            // dataGridView1
            //
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(13, 13);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(405, 290);
            this.dataGridView1.TabIndex = 0;

//Add the column header mouse cilck event handler

            this.dataGridView1.ColumnHeaderMouseClick += new
         System.Windows.Forms.
DataGridViewCellMouseEventHandler
         (dataGridView1_ColumnHeaderMouseClick);

            // Creating the custom datatable for binding
             dt = new DataTable();
             dt.Columns.Add(
new DataColumn("ID", System.Type.GetType("System.Int32")));
             dt.Columns.Add(new DataColumn("token_no", System.Type.GetType("System.String")));

            // Adding data to datatable
             DataRow dr = dt.NewRow();
             dr[
"ID"] = 1;
             dr[
"token_no"] = "Amit";
             dt.Rows.Add(dr);
             dr = dt.NewRow();
             dr[
"ID"] = 2;
             dr[
"token_no"] = "Ajit";
             dt.Rows.Add(dr);
             dr = dt.NewRow();
             dr[
"ID"] = 3;
             dr[
"token_no"] = "Rahul";
             dt.Rows.Add(dr);
             dr = dt.NewRow();
             dr[
"ID"] = 4;
             dr[
"token_no"] = "Sanjay";
             dt.Rows.Add(dr);
             dr = dt.NewRow();
             dr[
"ID"] = 5;
             dr[
"token_no"] = "Zuber";
             dt.Rows.Add(dr);
             dt.AcceptChanges();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {

            //Bind the datagridview with datatable
            dataGridView1.DataSource = dt;
        }
 
        /// <summary>
        /// Header click event handler that perform the sorting on DataGridView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
           
if (cntr % 2 == 0) //This condition applied for toggeling the Ascending and Descending sort
                dataGridView1.Sort(dataGridView1.Columns[e.ColumnIndex], ListSortDirection.Ascending);
            else
                dataGridView1.Sort(dataGridView1.Columns[e.ColumnIndex], ListSortDirection.Descending);
            cntr++;
        }
    }

Hope this article will help some developers dealing with DataGridView.

Cheers!!
 

Login to add your contents and source code to this article
post comment
     

Meko you would have to rewrite your sql to pull the tables in a single query. If you are using SQL Server and the SQL Strings are not being build dynamically you can build a stored Procedure and just have the progam call that stored proc. If the SQLs are being build dynamically then change the SQL Statement to be an insert to create tables then have a 3rd sql pull the final dataset for the datagrid. (Just make sure to drop the table when you are done) Also if there is not a common field to join them you can create one by putting a 1 in a cummy column and using that as the join.

Posted by Thomas Dec 07, 2011

I have two sqlquery string result and i would like to fill the 1st result in to dataGridView1.Columns1 and the 2nd in to dataGridView1.Columns2 some one can help me on this issue?

Posted by meko weldys Dec 07, 2011

Actually my experience with DataGridView in windows form applications is that if you click on the header it automatically sorts the data At least in visual studio 2005. Maybe it is different with .net or web based applications.

Posted by Thomas Sep 14, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.