在DataGridView中禁用列标题排序的最佳方法

我需要在DataGridView禁用列标题排序。

我们可以通过设置各个列的属性来实现

 BalancesGridView.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable; 

如果是这种情况,那么我将不得不遍历所有列。

有没有更好的办法 ?

不,我认为直接在列上设置SortMode就好了。 但老实说,谁在乎呢? 一个简单的循环有什么坏处?

这有什么不好的? 如果您不喜欢循环遍历列或者您有多个DataGridView,则可以为此编写扩展方法:

 public static class DatatGridViewExtensions { public static void SetColumnSortMode(this DataGridView dataGridView, DataGridViewColumnSortMode sortMode) { foreach (var column in dataGridView.Columns) { column.SortMode = sortMode; } } } 

像这样用它:

 BalancesGridView.SetColumnSortMode(DataGridViewColumnSortMode.NotSortable); 

我不知道为什么没有人建议你Linq这样做的方式:

 BalancesGridView.Columns.Cast().ToList().ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable); 

好吧,这有点旧,但循环设置单个列排序模式有一点问题,例如,您允许用户添加更多列,然后您必须再次重新循环它,或者找到添加的列并设置它的sortmode。 这是一项更多的工作。

我找到的解决方案就像这个链接: 单击DataGridView列标题时禁用排序

在其中,您只需为该DataGridView添加ColumnAdded的事件处理程序,因此每次datagrid添加列时,它都会自动设置为不可排序

这实际上就像@ OldDog的答案一样,区别在于他的回答中,sortmode是以迂回的方式设置的。

 Private Sub DataGridView1_ColumnAdded(sender As Object, e As DataGridViewColumnEventArgs) Handles DataGridView1.ColumnAdded e.Column.SortMode = DataGridViewColumnSortMode.NotSortable End Sub 

我说循环遍历列并不是一个很好的答案,特别是如果您的数据源不时发生变化。 ColumnAdded事件中的一行代码可以解决这个问题:

 e.Column.SortMode = DataGridViewColumnSortMode.NotSortable 

我今天遇到了这个问题。 我编写了这个方法并在表单加载事件上调用它。

  public void DisableGridviewSorting(DataGridView grid, int index) { //Index = DataGridView.Columns.Count for (int i = 0; i < index; i++) { grid.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; } } 

除非你使用绑定数据,否则无论你怎么做,看起来你几乎都在循环使用DataGridView。 然后,您可以为每个列设置不可排序。

如果在运行时构建DataGridView,则可以在使用ColumnAdded事件添加列时禁用列排序:

 private void BalancesGridView_ColumnAdded(object sender, System.Windows.Forms.DataGridViewColumnEventArgs e) { e.Column.SortMode = DataGridViewColumnSortMode.NotSortable; } 

我这样做了:

 private void gvItReq_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { for (int colIdx = 0; colIdx < gvItReq.Columns.Count; colIdx++) gvItReq.Columns[colIdx].SortMode = DataGridViewColumnSortMode.NotSortable; } 

在VB中,我使用一个小子程序,我为每个dgv调用,我希望列不可移动:

 Public Sub subNo_Sort_DGV_Columns(dgv As DataGridView) For intColumn_Count As Integer = 1 To dgv.Columns.Count - 1 dgv.Columns(intColumn_Count).SortMode = _ DataGridViewColumnSortMode.NotSortable Next End Sub 

我发现阻止排序的最好方法是定义是当你认为你需要处理很多列时将它定义为for循环。

 for (int i = 0; i < 10; i++) { dataGridView.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; }