DataView 排序 - 当列名称未知时如何排序
我需要有关如何解决在 C# 中对 DataView 进行排序时遇到的问题的建议。
我需要向 DataView 添加排序属性,因为稍后在 DataView 上调用 Find 时需要它(需要指定排序属性才能工作)。我需要 Find 才能将 DataRow 正确映射到 DataGridViewRow。我目前只使用行索引映射到 DataGridViewRow,但如果用户物理移动行或更改 DataGridView (UI) 中的排序顺序,则这在所有情况下都不起作用,因为这样 id 不再匹配/地图。
当我创建 DataView 时,我加载一个 DataTable 以传入进行创建。该数据表可以是任何形式,我不知道数据表包含什么列和行。因此,如果我不知道要排序的任何列名称,则无法创建排序。
我正在考虑只采用第一个列名称(列[0]) - 无论它是什么并使用它进行排序。但这似乎有点粗略,不是吗?
我的问题是,当列名未知时,是否有更好的方法来确定对 DataView 进行排序?
谢谢!
I need advice on how to go about a problem I have with sorting a DataView in C#.
I need to add a sort property to my DataView because I later need it when I call a Find on the DataView (which needs to have a sort property specified in order to work). I need the Find in order to properly map a DataRow to a DataGridViewRow. I currently just use the row index to map to the DataGridViewRow, but this won't work in all cases if the user physically moves rows, or changes the sort order in the DataGridView (UI) because then the ids no longer match-up/map.
When I create the DataView, I load in a DataTable to pass in for creation. This DataTable can be of any form, I do not know what the DataTable contains for columns and rows. Therefore, I cannot create a sort if I don't know any column names to sort by.
I was thinking of just taking the first column name (column[0]) - no matter what it is and using that to sort. But this seems kinda sketchy, no?
My question is, is there a better way to determine what to sort my DataView by when column names are unknown?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我还没有尝试过,但由于它根据您传入的列名进行排序,您是否不能根据索引进行排序,例如:
dataview.Sort = dataview.Table.Columns[index].ColumnName + “降序”;
I haven't tried it, but since it sorts based on the column name you pass in, couldn't you sort based on index with something like:
dataview.Sort = dataview.Table.Columns[index].ColumnName + " DESC";