Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

c# - DataGridView Column sorting with Business Objects

I am setting-up my DataGridView like this:

        jobs = new List<DisplayJob>();

        uxJobList.AutoGenerateColumns = false;
        jobListBindingSource.DataSource = jobs;
        uxJobList.DataSource = jobListBindingSource;

        int newColumn;
        newColumn = uxJobList.Columns.Add("Id", "Job No.");
        uxJobList.Columns[newColumn].DataPropertyName = "Id";
        uxJobList.Columns[newColumn].DefaultCellStyle.Format = Global.JobIdFormat;
        uxJobList.Columns[newColumn].DefaultCellStyle.Font = new Font(uxJobList.DefaultCellStyle.Font, FontStyle.Bold);
        uxJobList.Columns[newColumn].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
        uxJobList.Columns[newColumn].Width = 62;
        uxJobList.Columns[newColumn].Resizable = DataGridViewTriState.False;
        uxJobList.Columns[newColumn].SortMode = DataGridViewColumnSortMode.Automatic;
        :
        :

where the DisplayJob class looks like:

    public class DisplayJob
{
    public DisplayJob(int id)
    {
        Id = id;
    }

    public DisplayJob(JobEntity job)
    {
        Id = job.Id;
        Type = job.JobTypeDescription;
        CreatedAt = job.CreatedAt;
        StartedAt = job.StartedAt;
        ExternalStatus = job.ExternalStatus;
        FriendlyExternalStatus = job.FriendlyExternalStatus;
        ExternalStatusFriendly = job.ExternalStatusFriendly;
        CustomerName = job.Customer.Name;
        CustomerKey = job.Customer.CustomerKey;
        WorkAddress = job.WorkAddress;
        CreatedBy = job.CreatedBy;
        CancelledAt = job.CancelledAt;
        ClosedAt = job.ClosedAt;
        ReasonWaiting = job.ReasonWaiting;
        CancelledBy = job.CancelledBy;
        CancelledReason = job.CancelledReason;
        DisplayCreator = Global.GetDisplayName(CreatedBy);
        ActionRedoNeeded = job.ActionRedoNeeded;
        if (job.Scheme != null)
        {
            SchemeCode = job.Scheme.Code;
        }

    }

    public int Id { get; private set; }
    public string Type { get; private set; }
    public DateTime CreatedAt { get; private set; }
    public DateTime? StartedAt { get; private set; }
    public string ExternalStatus { get; private set; }
    public string FriendlyExternalStatus { get; private set; }
    public string ExternalStatusFriendly { get; private set; }
    public string CustomerName { get; private set; }
    public string CustomerKey { get; private set; }
    public string WorkAddress { get; private set; }
    public string CreatedBy { get; private set; }
    public DateTime? CancelledAt { get; private set; }
    public DateTime? ClosedAt { get; private set; }
    public string CancelledBy { get; private set; }
    public string ReasonWaiting { get; private set; }
    public string DisplayCreator { get; private set; }
    public string CancelledReason { get; private set; }
    public string SchemeCode { get; private set; }
    public bool ActionRedoNeeded { get; private set; }
}

However the column sorting does not work. What is the best way to get this working?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to support sorting and searching on the collection, all it takes it to derive a class from your BindingList parameterized type, and override a few base class methods and properties.

The best way is to extend the BindingList and do those following things:

protected override bool SupportsSearchingCore
{
    get
    {
        return true;
    }
}

protected override bool SupportsSortingCore
{
    get { return true; }
}

You will also need to implement the sort code:

ListSortDirection sortDirectionValue;
PropertyDescriptor sortPropertyValue;

protected override void ApplySortCore(PropertyDescriptor prop, 
    ListSortDirection direction)
{
    sortedList = new ArrayList();

    // Check to see if the property type we are sorting by implements
    // the IComparable interface.
    Type interfaceType = prop.PropertyType.GetInterface("IComparable");

    if (interfaceType != null)
    {
        // If so, set the SortPropertyValue and SortDirectionValue.
        sortPropertyValue = prop;
        sortDirectionValue = direction;

        unsortedItems = new ArrayList(this.Count);

        // Loop through each item, adding it the the sortedItems ArrayList.
        foreach (Object item in this.Items) {
            sortedList.Add(prop.GetValue(item));
            unsortedItems.Add(item);
        }
        // Call Sort on the ArrayList.
        sortedList.Sort();
        T temp;

        // Check the sort direction and then copy the sorted items
        // back into the list.
        if (direction == ListSortDirection.Descending)
            sortedList.Reverse();

        for (int i = 0; i < this.Count; i++)
        {
            int position = Find(prop.Name, sortedList[i]);
            if (position != i) {
                temp = this[i];
                this[i] = this[position];
                this[position] = temp;
            }
        }

        isSortedValue = true;

        // Raise the ListChanged event so bound controls refresh their
        // values.
        OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
    }
    else
        // If the property type does not implement IComparable, let the user
        // know.
        throw new NotSupportedException("Cannot sort by " + prop.Name +
            ". This" + prop.PropertyType.ToString() + 
            " does not implement IComparable");
}

If you need more information you can always go there and get all explication about how to extend the binding list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...