我怎样才能在DataGrid中按字母顺序列标题排序? C#

编程入门 行业动态 更新时间:2024-10-28 01:26:25
本文介绍了我怎样才能在DataGrid中按字母顺序列标题排序? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含列标题的排序列表,我如何重新排列我的datagridview,所以它是在排序列表的相同的顺序?

I have a sorted list that contains the column headers, how do I rearrange my datagridview so it is in the same order as my sorted list?

尝试下面的代码,但这并不总是工作,一些列没有正确排序。非常感谢您的帮助。

I've tried the code below but this doesn't always work, some columns are not sorted correctly. Thanks for any help with this.

sortedColumnNames.Sort(); foreach (DataGridViewColumn col in dataGridView1.Columns) { col.DisplayIndex = sortedColumnNames.IndexOf(col.HeaderText); }

sortedColumnNames: athens crete corfu kefalonia mykonos 罗得斯 santorini skiathos zante

sortedColumnNames: athens crete corfu kefalonia mykonos rhodes santorini skiathos zante

推荐答案

我不能告诉你的问题是 SortedColumnNames 没有正确排序(它不是),或者如果列被分配一个不同的

I can't tell if your problem is that SortedColumnNames isn't sorted properly (which it's not), or if the columns are being assigned a different order than what appears in the list.

如果是后者,则可以假设是因为您正在修改列表中的项目顺序。集合,因为你正在迭代它。虽然我没有看到这种情况发生在我正在运行的任何测试中。

If it's the latter, it could conceivably be because you're modifying the order of items in the collection as you're iterating over it. Though I'm not seeing that happen in any of the tests I'm running.

作为一般规则,我不会混乱成员资格或我迭代的集合的顺序。我以这种方式实现列排序:

Just as a general rule, I don't mess with the membership or order of a collection that I'm iterating over. I implement column-sorting this way:

void SortDataGridViewColumns(DataGridView dgv) { var list = from DataGridViewColumn c in dgv.Columns orderby c.HeaderText select c; int i = 0; foreach (DataGridViewColumn c in list) { c.DisplayIndex = i++; } }

更多推荐

我怎样才能在DataGrid中按字母顺序列标题排序? C#

本文发布于:2023-06-10 05:46:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/608255.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字母   顺序   标题   DataGrid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!