C# DataGridViewColumn 初始排序方向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1193929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataGridViewColumn initial sort direction
提问by lnediger
I'm working in VS2008 on a C# WinForms app. By default when clicking on a column header in a DataGridView it sorts that column Ascending, you can then click on the column header again to sort it Descending.
我正在 VS2008 中使用 C# WinForms 应用程序。默认情况下,当单击 DataGridView 中的列标题时,它对该列进行升序排序,然后您可以再次单击列标题以对其进行降序排序。
I am trying to reverse this, so the initial click sorts Descending then the second click sorts Ascending and I haven't been able to figure out how to do this. Does anyone know?
我试图扭转这一点,所以最初的点击排序降序,然后第二次点击排序升序,我一直无法弄清楚如何做到这一点。有人知道吗?
Thanks
谢谢
采纳答案by SwDevMan81
You can set the HeaderCell SortGlyphDirection to Ascending, and then the next click will give you the descending order. The default is none.
您可以将 HeaderCell SortGlyphDirection 设置为 Ascending,然后下次单击会给您降序。默认值为无。
dataGridView1.Sort(Column1, ListSortDirection.Ascending);
this.Column1.HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending;
回答by Vivek
Take a look at DataGridView.SortCompare
.
See slightly modified version of the msdn example below:
看看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;
}
回答by Christopher Galpin
foreach (DataGridViewColumn column in DataGridView1.Columns)
{
column.SortMode = DataGridViewColumnSortMode.Programmatic;
}
and
和
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;
}
}
回答by sam
I suggest below code
我建议下面的代码
MyDGV.Sort(MyDGV.Columns[column_Index], ListSortDirection.Ascending);