DataGridView实现点击列头升序和降序排序

  private void dgv_Users_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)

  {

  DataGridView dgv = sender as DataGridView;

  if (dgv.Columns[e.ColumnIndex].SortMode == DataGridViewColumnSortMode.Programmatic)

  {

  string columnBindingName = dgv.Columns[e.ColumnIndex].DataPropertyName;

  switch (dgv.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection)

  {

  case System.Windows.Forms.SortOrder.None:

  case System.Windows.Forms.SortOrder.Ascending:

  CustomSort(columnBindingName, "desc");

  dgv.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Descending;

  break;

  case System.Windows.Forms.SortOrder.Descending:

  CustomSort(columnBindingName, "asc");

  dgv.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending;

  break;

  }

  }

  }

  ///

  /// 自定义排序

  ///

  /// 绑定的字段名

  /// 排序方式 asc 升序 desc 降序

  private void CustomSort(string columnBindingName, string sortMode)

  {

  DataTable dt = this.dgv_Users.DataSource as DataTable;

  DataView dv = dt.DefaultView;

  dv.Sort = columnBindingName + " " + sortMode;

  this.dgv_Users.DataSource = dv.ToTable();

  this.dgv_Users.Refresh();

  }