Sorting in Gridview Using asp.net
Sorting in Gridview Using asp.net
Using soring feature of gridview, we can easily rearrange
our data in any order either ascending or descending. Using this we can arrange
any type of data like numeric, alphabetic or alphanumeric.
Step 1: Design web form .aspx page
<asp:GridView ID="gr" runat="server" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="WhiteSmoke" Width="40%" AllowSorting="true" OnSorting="gr_Sorting" >
<HeaderStyle BackColor="#3366ff" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone" SortExpression="phone">
<ItemTemplate>
<asp:Label ID="lbl_phone" runat="server" Text='<%#Eval("Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount" SortExpression="amount">
<ItemTemplate>
<asp:Label ID="lbl_city" runat="server" Text='<%#Eval("Amount") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Step 2: Logic on .CS page
static bool a, b;
protected void Page_Load(object sender, EventArgs e)
{
bind_gr();
}
public void bind_gr()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Amount");
dt.Columns.Add("Phone");
dt.Rows.Add("Kandy", "12", "8802***2564");
dt.Rows.Add("Sam", "25", "545502*2544");
dt.Rows.Add("Izhar", "32", "95802*2452");
dt.Rows.Add("Vineet", "10.2", "88022564***");
dt.Rows.Add("Kandy", "0.12", "8802***2564");
dt.Rows.Add("Sam", "12", "545502*2544");
dt.Rows.Add("Izhar", "215", "95802*2452");
dt.Rows.Add("Vineet", "11.00", "88022564***");
dt.Rows.Add("Kandy", "0.12", "8802***2564");
dt.Rows.Add("Sam", "12", "545502*2544");
dt.Rows.Add("Izhar", "215", "95802*2452");
dt.Rows.Add("Vineet", "11.00", "88022564***");
dt.Rows.Add("Kandy", "0.12", "8802***2564");
dt.Rows.Add("Sam", "12", "545502*2544");
dt.Rows.Add("Izhar", "215", "95802*2452");
dt.Rows.Add("Vineet", "11.00", "88022564***");
gr.DataSource = dt;
gr.DataBind();
}
protected void gr_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable grd_sort = (DataTable)gr.DataSource;
if (grd_sort != null)
{
DataView dvSortedView = new DataView(grd_sort);
dvSortedView.Sort = e.SortExpression +
" " + getSortDirectionString(a);
gr.DataSource = dvSortedView;
gr.DataBind();
a = !a;
}
}
private String getSortDirectionString(bool sortd)
{
string newSortDirection = String.Empty;
if (sortd == false)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
Comments
Post a Comment