I have a data grid view with columns : IdentityNumber , Name , Date . Each column represents different types of values . identityNumner is an integer , Name is a string , and date is DateTime.
My goal is to click on a column's header and the sort will be done accoding to the types above. The auto sort without doing anything is sort by string as I can see . but how do I achive my goal ?
I have found a solution for my problem . Please check the answer below .
Found a solution for my problem :
Inside the ctor of the form I registered the data grid view's SortCompare event :
DataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(MyCustomSortFunction);
The custom function Iv'e build is :
void MyCustomSortFunction(object sender, DataGridViewSortCompareEventArgs e)
{
try
{
// checks if the column's header that was pressed is the identity number -
// If so , sort as integer .
if (e.Column.Name == "colIdentity")
{
int a = Convert.ToInt32(e.CellValue1.ToString());
int b = Convert.ToInt32(e.CellValue2.ToString());
e.SortResult = a.CompareTo(b);
e.Handled = true;
}
// checks if the column's header that was pressed is the date -
// If so , sort as DateTime .
else if (e.Column.Name == "colHDate")
{
DateTime c = Convert.ToDateTime(e.CellValue1.ToString());
DateTime d = Convert.ToDateTime(e.CellValue2.ToString());
e.SortResult = c.CompareTo(d);
e.Handled = true;
}
}
catch
{ }
}
Hope my answer will help someone :-) Shuki .