C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Grid View Sorting


Posted Date: 30 Aug 2008      Total Responses: 3

Posted By: amit chaudhary       Member Level: Silver     Points: 1


How to do Sorting in Grid view while using Template Fields and without using any Data Source.




Responses

Author: Rajesh(March-2008 Winner)    30 Aug 2008Member Level: GoldRating:     Points: 6
Hi ,


GridView's built-in sorting can be enabled by simply setting its AllowSorting property to true and setting its DataSourceId property to a data source control that supports sorting.

Here is an example declaration that sets up automatic sorting for a GridView control.

Listing 1

<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1"
DataKeyNames="au_id" AutoGenerateColumns="False" AllowSorting="true"
PageSize="6" Runat="Server">
<Columns>
<asp:BoundField ReadOnly="true" HeaderText="au_id" DataField="au_id"
SortExpression="au_id"></asp:BoundField>
<asp:BoundField HeaderText="au_lname" DataField="au_lname"
SortExpression="au_lname"></asp:BoundField>
<asp:BoundField HeaderText="city" DataField="city"
SortExpression="city"></asp:BoundField>
<asp:BoundField HeaderText="state" DataField="state"
SortExpression="state"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" SelectCommand="SELECT * FROM [authors]"
ConnectionString="<%$ConnectionStrings:AppConnectionString1 %>"
Runat="Server">
</asp:SqlDataSource>

This enables sorting on the GridView columns that have a SortExpression specified. Clicking on the column header link toggles the sort direction. However, the standard GridView control does not present any visual cues for the sort direction (ascending or descending) and does not support sorting on more than one column (which is not an uncommon need when presenting data across multiple pages).



Author: Vidhya    30 Aug 2008Member Level: GoldRating:     Points: 6
hi,

LINQ provides querying capabilities on a generic level, the above problems are no problem. Because LINQ to objects can handle *any* enumerable objects, and LINQ to SQL is smart enough to pass the sorting logic on to SQL Server, you win no matter what.

For example, imagine if the data source was a collection of MembershipUsers (via the Membership.GetUsers method). Here's how easy it would be to sort using LINQ and the OrderBy method:

// Using LINQ to sort by a user's name.
myGridView.DataSource = Membership.GetUsers()
.OfType<MembershipUser>()
.OrderBy(user => user.Name);
That was very easy to do, but that's because we know the data type of our source at compile time. But if we are going to make a generic "self sorting GridView", then we have to build our functionality with the limitation of not knowing the data type of the data source or the name of the field that is being sorted. So we'll need to reconstruct this functionality at runtime by building "expression trees" (the power behind LINQ).

Step One - Build Our GridView Control
To begin with, let's build a basic control that inherits from GridView , and stub out a placeholder to put our sorting logic.

public class SelfSortingGridView : GridView
{
protected override void OnSorting(GridViewSortEventArgs e)
{
// Our code below is going to live here...
}
}
Now that we have our custom GridView control ready to go, we can move on to step two.

Step Two - Creating an Expression to Sort With
As was stated earlier, we need to build an expression that will tell LINQ how we want to sort our data source. There are a few tricky issues here that we need to identify and overcome. If we try to copy the example found in this blog post to reproduce our sorting example at the top of this article, we would get half-way there:

// Using a custom LINQ expression to sort by a user's name.
var param = Expression.Parameter(typeof(MembershipUser), "user");

// By the way, if you don't "box" the return type into an object,
// you'll get a runtime error when you try to sort by a value type.
// So instead of doing this (which would be expected):
var sortExpression = Expression.Lambda<Func<MembershipUser, object>
(Expression.Property(param, "Name"), param);

// I'm going to do this:
var sortExpression = Expression.Lambda<Func<MembershipUser, object>
(Expression.Convert(Expression.Property(param, "Name"), typeof(object)), param);

// And then I can sort my data source:
myGridView.DataSource = Membership.GetUsers()
.OfType<MembershipUser>().OrderBy(sortExpression);
So we've solved one issue - that of finding the property to sort with by it's name. The "Expression.Property" method above did that for us. Now, we have to solve the second issue - not knowing what the data type of the data source will be until runtime. To solve this in the fewest lines of code, I'm going to make a custom generic class that will create the sort expression for us so that we can simply supply the type at runtime.

public class GenericSorter<T>
{
public IEnumerable<T> Sort(IEnumerable<T> source, string sortBy)
{
var param = Expression.Parameter(typeof(T), "item");

var sortExpression = Expression.Lambda<Func<T, object>>
(Expression.Convert(Expression.Property(param, sortBy), typeof(object)), param);

return source.AsQueryable<T>().OrderBy<T, object>(sortExpression);
}
}
Beautiful! Notice that because we are using a generic class, we can tell the compiler that we want to use the type "T" (whatever "T" will be at runtime, we don't care)! So, if I wanted to create an instance of my GenericSorter class at runtime, passing in a type that I won't know until runtime, and then call the "Sort" method, I would just do some simple reflection as will be shown below.

For simplicities sake, the data source is stored in a variable called "_data". You can download the whole source code at the end of the article to see exactly how it's done. Here's a sample of the code:

// Give me the data type of the GridView's data source.
Type dataSourceType = _data.GetType();

// Determine the data type of the items in the data source at runtime.
Type dataItemType = typeof(object);

if (dataSourceType.HasElementType)
{
// Get the element type if the data source is an array.
dataItemType = dataSourceType.GetElementType();
}
else if (dataSourceType.IsGenericType)
{
// Get the element type if the data source is a generic list.
dataItemType = dataSourceType.GetGenericArguments()[0];
}

// Create an instance of the GenericSorter class passing in the data item type.
Type sorterType = typeof(GenericSorter<>).MakeGenericType(dataItemType);

var sorterObject = Activator.CreateInstance(sorterType);

// Now I can call the "Sort" method passing in my runtime types.
this.DataSource = sorterType.GetMethod("Sort", new Type[] { dataSourceType, typeof(string) })
.Invoke(sorterObject, new object[] { _data, e.SortExpression });

this.DataBind();

Happy programming!



Author: Lokesh    25 Oct 2008Member Level: SilverRating:     Points: 6
here is aspx page, you can use in value as u use in ur table field name this is possible through coding
<h2>Sorting with Coding</h2>
<asp:DropDownList ID="ddlsorting" runat="server">
<asp:ListItem Value="empid">Employee ID</asp:ListItem>
<asp:ListItem Value="empname">Name</asp:ListItem>
<asp:ListItem Value="empage">Age</asp:ListItem>
<asp:ListItem Value="empcity">City</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnsorting" runat="Server" Text="Sort" OnClick="btnsorting_Click" />
<asp:GridView ID="gridsorting" runat="Server" DataSourceID="SqlDataSource1"></asp:GridView>




here is cs file:

protected void btnsorting_Click(object sender, EventArgs e)
{
gridsorting.Sort(ddlsorting.SelectedItem.Value, SortDirection.Ascending);
}



Here is another example through aspx only without using cs page:
<asp:GridView ID="grid1" runat="Server" AllowSorting="true" AllowPaging="True" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" PageSize="10" AutoGenerateSelectButton="true">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="empid" HeaderText="Employee ID" SortExpression="empid" />
<asp:BoundField DataField="empname" HeaderText="Name" SortExpression="empname" />
<asp:BoundField DataField="empage" HeaderText="Age" SortExpression="empage" />
<asp:BoundField DataField="empcity" HeaderText="City" SortExpression="empcity" />
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Personal %>"
SelectCommand="SELECT [empid], [empname], [empage], [empcity] FROM [emp]"></asp:SqlDataSource>

In it sqldatasource used only for fetching data from table. I give connection string in web.config it depend on you how u can give connection string.



Post Reply
You must Sign In to post a response.
Next : please give the code...its very urgent.....
Previous : Send SMS
Return to Discussion Forum
Post New Message
Category: ASP.NET

Related Messages



dotNet Slackers   BizTalk Adaptors    Web Design

SPOC

Contact Us    Privacy Policy    Terms Of Use