问题
I have a datagridview that contain 3 columns. But I hv not bind a datasource to datagridview. It has three columns.
EmpName,InTime,OutTime
I can edit EmpName in datagridview.
I want to sort the content in the datagridview after i edit a row.
I want to sort first by EmpName and then by InTime. The time is in AM , PM Time format (Ex: 2:00 PM).
I can sort data by only one column. I have used,
dgvSchedule.Sort(dgvSchedule.Columns[0],ListSortDirection.Ascending);
But how to sort by multiple columns. Specially when the time is in AM PM format. Please help me.
Thanks in advance.
回答1:
Implement the IComparer
somehow like this:
private class CustomComparer : IComparer
{
private static int SortOrder = 1;
public CustomComparer(SortOrder sortOrder)
{
SortOrder = sortOrder == SortOrder.Ascending ? 1 : -1;
}
public int Compare(object x, object y)
{
DataGridViewRow row1 = (DataGridViewRow)x;
DataGridViewRow row2 = (DataGridViewRow)y;
int result = row1.Cells["EmpName"].Value.ToString().CompareTo(
row2.Cells["EmpName"].Value.ToString());
if ( result == 0 )
{
result = DateTime.ParseExact(
row1.Cells["InTime"].Value.ToString(),
"h:mm tt",
CultureInfo.InvariantCulture).TimeOfDay
.CompareTo(
DateTime.ParseExact(
row2.Cells["InTime"].Value.ToString(),
"h:mm tt",
CultureInfo.InvariantCulture).TimeOfDay);
}
return result * SortOrder;
}
Usage is:
dgvSchedule.Sort(new CustomComparer(ListSortDirection.Ascending));
来源:https://stackoverflow.com/questions/21728420/sort-datagridview-by-two-columns