2
Answers

Custom Sorting in DataGridView by using Sort Compare Event

Piyush Vaishnav

Piyush Vaishnav

16y
18.8k
1

Hi,

   I am new to datagridview. I want custom sorting on one column of datagridview. For that i have written program. Everything is fine but SortCompare Event is not firing.

Firstly i created one Datagridview in Windows Application and then populated that one. Here is the code:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Collections;

 

namespace MyWinApp

{

public partial class Form1 : Form

{

DataTable dt;

public Form1()

{

InitializeComponent();

dt = null;

}

private void Form1_Load(object sender, EventArgs e)

{

dt = new DataTable("Employees");

DataColumn dc = dt.Columns.Add("EmpNo", typeof(Double));

dt.Columns.Add("EmpName", typeof(String));

dt.Columns.Add("DateofJoining", typeof(String));

DataRow row1 = dt.NewRow();

row1["EmpNo"] = 1937;

row1["EmpName"] = "Piyush";

DateTime DT1 = DateTime.Now;

row1["DateofJoining"] = Convert.ToString(DT1);

dt.Rows.Add(row1);

DataRow row2 = dt.NewRow();

row2["EmpNo"] = 1938;

row2["EmpName"] = "Sanjib";

DateTime DT2 = DateTime.Now.AddDays(12);

row2["DateofJoining"] = Convert.ToString(DT2);

dt.Rows.Add(row2);

DataRow row3 = dt.NewRow();

row3["EmpNo"] = 1939;

row3["EmpName"] = "Bala";

DateTime DT3 = DateTime.Now.AddHours(05).AddYears(07);

row3["DateofJoining"] = Convert.ToString(DT3);

dt.Rows.Add(row3);

DataRow row4 = dt.NewRow();

row4["EmpNo"] = 1940;

row4["EmpName"] = "Manas";

DateTime DT4 = DateTime.Now.AddMonths(03);

row4["DateofJoining"] = Convert.ToString(DT4);

dt.Rows.Add(row4);

}

private void button1_Click(object sender, EventArgs e)

{

dataGridView1.DataSource = dt;

dataGridView1.VirtualMode = false;

dataGridView1.Columns["DateofJoining"].SortMode = DataGridViewColumnSortMode.Programmatic; //dataGridView1.Columns["DateofJoining"].DefaultCellStyle.Format = "G";

}

private void button2_Click(object sender, EventArgs e)

{

Application.Exit();

}

private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)

{

e.SortResult = System.String.Compare(

e.CellValue1.ToString(), e.CellValue2.ToString()); // If the cells are equal, sort based on the column.

if (e.SortResult == 0 && e.Column.Name != "DateofJoining")

{

e.SortResult = System.String.Compare(

dataGridView1.Rows[e.RowIndex1].Cells["DateofJoining"].Value.ToString(),

dataGridView1.Rows[e.RowIndex2].Cells["DateofJoining"].Value.ToString());

}

e.Handled = true;

}

}

}

I have made virtual mode as false and sort mode  as programmatic.

Thanx in advance........

if u want to share some another technique for the same...then urs welcome.......

Answers (2)
Next Recommended Forum