1,将需要进行排序的列做属性的设置
this.colUserName.SortMode = DataGridViewColumnSortMode.Programmatic;
2,添加列的事件
//点击列头进行排序
private void dgv_NoSignalSelect_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
int nColumnIndex = e.ColumnIndex;
if (dgv_NoSignalSelect.Columns[nColumnIndex].SortMode != DataGridViewColumnSortMode.Programmatic)
{
return;
}
switch (dgv_NoSignalSelect.Columns[nColumnIndex].HeaderCell.SortGlyphDirection)
{
case SortOrder.None:
case SortOrder.Ascending:
//在这里加入排序的逻辑
OrderTableOgDgv(nColumnIndex, "asc");
//设置列标题的状体
dgv_NoSignalSelect.Columns[nColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.Descending;
break;
default:
//在这里加入排序的逻辑
OrderTableOgDgv(nColumnIndex, "desc");
//设置列标题的状体
dgv_NoSignalSelect.Columns[nColumnIndex].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
break;
}
}
3,下面是上面应用到的排序算法
/// <summary>
/// 给dgv_NoSignalSelect按列排序
/// </summary>
/// <param name="nColumnIndex"></param>
/// <param name="orderCmd"></param>
private void OrderTableOgDgv(int nColumnIndex, string orderCmd)
{
DataTableEx dtex = this.dgv_NoSignalSelect.SourceDataTable;
dtex = UserQueueServer.OrderTable(dtex, dgv_NoSignalSelect.Columns[nColumnIndex].Name, orderCmd);
this.dgv_NoSignalSelect.SourceDataTable = dtex;
this.dgv_NoSignalSelect.Refresh();
}
public Class UserQueueServer{
/// <summary>
/// 对DataTable排序
/// </summary>
/// <param name="dt">DataTableEx</param>
/// <param name="columnname">排序的列名称</param>
/// <param tyoe="type">排序类型 "desc"-降序 "asc"-升序</param>
/// <returns></returns>
public static DataTableEx OrderTable(DataTableEx dt, string columnname,string type)
{
DataTable ds = dt.Clone();
ds.Clear();
if (dt.Columns.Contains(columnname))
{
DataRow[] drs = dt.Select("1=1", columnname + " "+ type);
foreach (DataRow dr in drs)
{
ds.Rows.Add(dr.ItemArray);
}
}
return ds as DataTableEx;
}
}