https://blog.csdn.net/kucoffee12/article/details/88055919
C# DataGridView控件关闭列自动排序功能
当DataGridView绑定DataTable时,点击DataGridView表头的时候,DataGridView会自动排序(注意string按字符串排序的,不是按数值大小),但是对于绑定的DataTable并不会随着DataGridView的行顺序改变数据的顺序。
在DataGridView控件里面的属性关闭列自动排序是需要到对应列里面去设置SortMode属性为NotSortable的,对于绑定DataTable数据的并不适用,需要在绑定DataTable之后再代码里面关闭列自动排序。
DataGridViewTextBoxColumn 的默认排序模式是 Automatic。其他列类型的默认排序模式是 NotSortable。
控件属性设置:
编辑列–>选定列–>行为–>SortMode–>NotSortable
设置的代码如下:
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
- 1
- 2
- 3
- 4
首先是获取总共有多少列,然后通过循环将每一列的SortMode设置成不自动排序就可以了。这里总共有三个属性可供选择,一种就是默认的自动排序,一种是不排序,在就是通过程序控制排序,可以根据需要进行设置。
</div>