如何防止数据网格视图的排序

时间:2009-06-08 11:12:22

标签: winforms c#-2.0

我在Windows窗体上使用DataGridView。它只显示两列。默认情况下,在运行应用程序时,如果单击列标题,则datagridview将根据该列进行排序。但是,我想完全禁用网格视图上的排序。我无法找到可以设置sorted = false的属性,或类似的东西。

有谁能告诉我如何禁用网格视图排序?

谢谢:)

修改

我想可以将各列设置为NotSortable(下面的贴出答案)。它可以在网格视图级别完成,而不是单个列吗?

6 个答案:

答案 0 :(得分:21)

好的,找到了答案。对于每个列,我需要明确指定

this.dgv.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;

所以我在Helper类中编写了自己的函数

/// <summary>
/// Sets the sort mode for the data grid view by setting the sort mode of individual columns
/// </summary>
/// <param name="dgv">Data Grid View</param>
/// <param name="sortMode">Sort node of type DataGridViewColumnSortMode</param>
public static void SetGridViewSortState(DataGridView dgv, DataGridViewColumnSortMode sortMode)
{
    foreach (DataGridViewColumn col in dgv.Columns)
        col.SortMode = sortMode;
}

无论在哪里,我都需要使网格视图无法解决,我称之为:

Helper.SetGridViewSortState(this.dgv, DataGridViewColumnSortMode.NotSortable);

答案 1 :(得分:3)

For i = 0 To DataGridView1.Columns.Count - 1
    DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next i

web gridview有一个属性AllowSorting,这更容易!

答案 2 :(得分:2)

排序部分是数据源的一个特征。这种情况下的数据源是什么?也许是DataTable?一种选择就是使用不支持排序的数据源,这几乎就是所有这些。 List<T>BindingList<T>等 - 不提供排序。

如果你必须使用DataView,你可以(我猜)用自定义视图包装视图,重新实现IBindingList(为false返回SupportsSorting),但只是更改每列的值是很多更容易(到疯狂做其他任何事情......)

答案 3 :(得分:0)

或者您可以创建自己的函数

Private Sub NotSortGrid()

    For i = 0 To dgvUtil.Columns.Count - 1



        dgvUtil.Columns.Item(i).SortMode = DataGridViewColumnSortMode.NotSortable



    Next i

End Sub

答案 4 :(得分:-1)

您可以随时自行处理列标题点击和双击事件,并且不执行任何操作。

答案 5 :(得分:-1)

使用.NET 3.0,GridView有一个名为AllowSorting

的属性