2009-07-28 75 views
6

我正在VS2008中的C#WinForms應用程序中工作。默認情況下,當點擊DataGridView中的列標題時,會按升序對該列進行排序,然後您可以再次單擊列標題以對其進行降序排序。DataGridViewColumn初始排序方向

我想扭轉這種情況,所以最初的點擊排序降序然後第二次點擊排序升序,我一直無法弄清楚如何做到這一點。有人知道嗎?

謝謝

回答

7

您可以設置HeaderCell SortGlyphDirection爲升序,再下點擊會給你的降​​序排列。默認值是none。

dataGridView1.Sort(Column1, ListSortDirection.Ascending); 
this.Column1.HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending; 
+0

我相信這隻會改變「字形」不排序順序 - 即在列中顯示的圖像標題:▲或▼ – Vivek 2009-07-28 13:36:36

+0

嗯,你是對的,你必須對列進行排序,我更新 – SwDevMan81 2009-07-28 14:04:10

0

看看DataGridView.SortCompare。 請參見下面的MSDN例子稍作修改的版本:

private void dataGridView1_SortCompare(object sender, 
     DataGridViewSortCompareEventArgs e) 
    { 
     // Try to sort based on the cells in the current column. 
     e.SortResult = System.String.Compare(
      e.CellValue2.ToString(), e.CellValue1.ToString()); // descending sort 

     e.Handled = true; 
    } 
7
foreach (DataGridViewColumn column in DataGridView1.Columns) 
{ 
    column.SortMode = DataGridViewColumnSortMode.Programmatic; 
} 

private void DataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) 
{ 
    var column = DataGridView1.Columns[e.ColumnIndex]; 
    if (column.SortMode != DataGridViewColumnSortMode.Programmatic) 
     return; 

    var sortGlyph = column.HeaderCell.SortGlyphDirection; 
    switch (sortGlyph) 
    { 
     case SortOrder.None: 
     case SortOrder.Ascending: 
      DataGridView1.Sort(column, ListSortDirection.Descending); 
      column.HeaderCell.SortGlyphDirection = SortOrder.Descending; 
      break; 
     case SortOrder.Descending: 
      DataGridView1.Sort(column, ListSortDirection.Ascending); 
      column.HeaderCell.SortGlyphDirection = SortOrder.Ascending; 
      break; 
    } 
} 
1

我建議下面的代碼

MyDGV.Sort(MyDGV.Columns[column_Index], ListSortDirection.Ascending);