GridView Sort Associated with a List of Custom Shared Objects

I'm trying to figure out how to sort GridViewmultiple columns ( String, DateTime, Decimaletc.), which are tied to a common list of user objects.

Myobject.vb

Public Property Id
Public Property Name
Public Property Date
Public Property Amount

MyObjects.aspx.vb

gridView.DataSource = GetMyObjects()
gridView.DataBind()

Note : GetMyObjects()returns a ListfromMyObject

Basically, I need to be able to click on the column headers of the grid for sorting and sorting in the reverse order, and also be able to keep the sort direction in ViewStateso that the direction is saved every time I click on the column heading.

It seems I probably need to MyObjectimplement it IComparable, but I'm not quite sure how to put it all together.

- ?

+5
1

(AllowSorting) OnSorting.

. #, VB .

GridView:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting">
</asp:GridView>

OnSorting:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    GridView1.DataSource = GetObjects(e.SortDirection, e.SortExpression);
    GridView1.DataBind();
}

GetObjects List<MyObject>. , Linq. , GetObjects : ( , , )

private List<MyObject> GetObjects(SortDirection sd, string se)
{
    // Have we generated data before?
    if (SimulatedDB == null)
    {
        // Create a sample DB
        SimulatedDB = new List<MyObject>();
        var rnd = new Random();

        for (int i = 0; i < 20; i++)
        {
            var node = new MyObject();
            node.Id = i;
            node.Name = String.Format("Name {0}", i);
            node.CreationDate = DateTime.Now.AddDays(rnd.Next(100));
            node.Amount = (rnd.Next(1000) * rnd.NextDouble());

            SimulatedDB.Add(node);
        }
    }

    // Return sorted list
    if (sd == SortDirection.Ascending)
        return SimulatedDB.AsQueryable<MyObject>().OrderBy<MyObject>(se).ToList();
    else
        return SimulatedDB.AsQueryable<MyObject>().OrderByDescending<MyObject>(se).ToList();
}

, .

+5

All Articles