如何在执行 DataBind 之前对 DataSet 进行排序?

How can I sort a DataSet before doing a DataBind?(如何在执行 DataBind 之前对 DataSet 进行排序?)
本文介绍了如何在执行 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 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)