How can I sort a DataSet before doing a DataBind?(如何在执行 DataBind 之前对 DataSet 进行排序?)
问题描述
I have data coming from the database in the form of a DataSet
. I then set it as the DataSource
of a grid control before doing a DataBind()
. I want to sort the DataSet
/DataTable
on one column. The column is to complex to sort in the database but I was hoping I could sort it like I would sort a generic list i.e. using a deligate.
Is this possible or do I have to transfer it to a different data structure?
Edit I can't get any of these answer to work for me, I think because I am using .Net 2.0.
Because of how DataTable (and DataView) sorting works, you can't use the delegate approach directly. One workaround is to add a column to the data-table that represents the order, and set the value (per row) based on the desired sequence. You can then add a Sort to the view on this new column. For example (using LINQ to do the sort, just for brevity):
var sorted = table.Rows.Cast<DataRow>().OrderBy(row => your code);
int sequence = 0;
foreach(var row in sorted)
{
row["sequence"] = sequence++;
}
(if you have a typed data-set, then I don't think you need the Cast step, or you would use your typed DataRow subclass)
[edit to include 2.0]
In 2.0 (i.e. without LINQ etc) you could use a List<T>
to do the sort - a bit more long-winded, but:
List<DataRow> sorted = new List<DataRow>();
foreach(DataRow row in table.Rows)
{
sorted.Add(row);
}
sorted.Sort(delegate(DataRow x, DataRow y) { your code });
int sequence = 0;
foreach(DataRow row in sorted)
{
row["sequence"] = sequence++;
}
(again, substitute DataRow if you are using a typed data-set)
这篇关于如何在执行 DataBind 之前对 DataSet 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在执行 DataBind 之前对 DataSet 进行排序?


基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01