How to make asp:GridView sortable? - asp.net

i have an asp:GridView control, which i've set the AllowSorting="True" property on:
<asp:GridView ID="gridUsers" runat="server" PageSize="100" ShowHeaderWhenEmpty="True"
Width="100%" AllowSorting="True" onrowcreated="gridUsers_RowCreated"
onsorting="gridUsers_Sorting">
</asp:GridView>
At design time the grid looks sortable:
But at runtime only the middle column is sortable:
How do i make an asp:GridView sortable in ASP.NET?
Note: The asp:GridView with AllowSorting requires a Sorting event handler to be present:
protected void gridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
//asp:GridView will throw an exception if a Sorting event handler isn't present
}
Update: i realized what's special about the Description column. It's the only column whose display name is correct from the database as-is. The remaining columns i have to fix the display name to be presentable:
protected void gridUsers_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false; //UserGUID
e.Row.Cells[1].Text = "User name";
e.Row.Cells[2].Text = "Full name";
//3=Description
e.Row.Cells[4].Text = "E-mail";
e.Row.Cells[5].Text = "Active";
e.Row.Cells[5].Visible = false;
e.Row.Cells[6].Text = "Account type";
}
Now i just have to figure out the tricky part; and make columns sortable.

this code will definitely help you:
In the GridView, Make the Property AllowSorting = "True" and in the GridView Columns give like this
<asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" />
and also use the below coding:
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
string sortExpression = e.SortExpression;
ViewState["z_sortexpresion"] = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, "DESC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, "ASC");
}
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
private void SortGridView(string sortExpression, string direction)
{
DTSorting = new DataView(DTSorting, "", sortExpression + " " + direction, DataViewRowState.CurrentRows).ToTable();
gv.DataSource = DTSorting;
gv.DataBind();
}
public DataTable DTSorting
{
get
{
if (ViewState["Sorting"] != null)
{
return (DataTable)ViewState["Sorting"];
}
else
return null;
}
set
{
ViewState["Sorting"] = value;
}
}
Here, Consider "DTSorting" is the DataTable by which you binds the GridView "gv".

protected void gridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["SortedTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
gridUsers.DataSource = Session["SortTable"];
gridUsers.DataBind();
}
}
Adapted from this msdn example:

Related

Duplicate columns get created while clicking "Edit" in asp:GridView

I have asp:GridView where I am using AutoGenerateEditButton="True" property to edit the grid row. Now the issue is whenever I click Edit button, the columns are populating again. For example If there 4 columns and if I click Edit than same 4 columns will reappear.
.ASPX Code:
<asp:GridView ID="grdEmpDetail" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
OnRowEditing="grdEmpDetail_RowEditing"
OnRowCancelingEdit="grdEmpDetail_RowCancelingEdit"
OnRowUpdated="grdEmpDetail_RowUpdated"
AutoGenerateEditButton="True">
</asp:GridView>
Code Behind: To Dynamically bind data on grid
protected void Page_Load(object sender, EventArgs e)
{
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch
{
throw;
}
}
Handle Edit Mode:
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
this.grdEmpDetail.DataBind();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
this.grdEmpDetail.DataBind();
}
OUTPUT: This is fine
ISSUE : This is where I am getting issue.
What am I missing here?
You are not checking for IsPostBack in your databinding code. As a result, each time you post to the page that code is being executed again and again. So each time you will add more columns.
Modify your handler like so:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
// All of your existing code goes here
}
}
Edit
It's a little more complicated than that. You DO actually need to re-bind your DataGrid to the data source when you click edit, but you just don't want to add the columns again. This requires that you break up your code some so that the code for data-binding can be re-used without being tied to the column addition.
First, let's create a method specifically for adding columns that appear on an input DataTable:
private void AddColumnsToDataGrid(DataTable dt) {
foreach (var col in dt.Columns) {
if (col.ToString() == "ID"
|| col.ToString() == "First Name"
|| col.ToString() == "Last Name"
|| col.ToString() == "Business Phone"
|| col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
}
Next Create a Method for Databinding a DataTable to your grid:
private void DataBindGrid(DataTable dt) {
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
Now that you've extracted some of that code out, you can re-use these methods where appropriate, and only add columns one time:
Page Load Handler
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try {
DataTable dt = objBL.OrderDetail();
AddColumnsToDataGrid(dt);
DataBindGrid(dt);
} catch {
// Side Note: If you're just re-throwing the exception
// then the try/catch block is completely useless.
throw;
}
}
}
Editing Handlers
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
Try:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Fill_Grid();
}
}
protected Void Fill_Grid()
{
if (grdEmpDetail.Columns.Count > 0)
{
for (int n = 0; n < grdEmpDetail.Columns.Count; n++)
{
grdEmpDetail.Columns.RemoveAt(n);
}
grdEmpDetail.DataBind();
}
this.grdEmpDetail.AutoGenerateColumns = false;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch (exception e1)
{
}
}
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
Fill_Grid();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
Fill_Grid();
}

checkboxlist selectedindexchanged event c# not working

I've got a checkboxlist on my asp.net page. I'm populating it with countries. I've added a "SelectedIndexChanged" event that is supposed to check that if one of the selected countries is Africa, it should make a textbox visible, otherwise visible=false if it is not selected. I have changed the AutoPostback to true. But the problem that I'm having is that it is not doing an autopostback (it's not going into the method at all). Could somebody please help me on this?
This is what I've done:
<div id="div1" style="overflow-x:auto; width:100%; max-width:100%; height:150px; max-height:150px;" runat="server">
<asp:CheckBoxList ID="lstLocations" CssClass="CheckBoxList" runat="server" Width="40%" Height="100%" AutoPostBack="True" OnSelectedIndexChanged="lstLocations_SelectedIndexChanged" >
</asp:CheckBoxList>
</div>
Populating the checkboxlist:
private void CreateRegionList()
{
lstLocations.Items.Clear();
cn = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand("SELECT ID, Region FROM CanonSALeads_Region ORDER BY Region", cn);
cn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
lstLocations.AutoPostBack = false;
lstLocations.CellPadding = 5;
lstLocations.CellSpacing = 5;
lstLocations.RepeatColumns = 1;
lstLocations.RepeatDirection = RepeatDirection.Vertical;
lstLocations.RepeatLayout = RepeatLayout.Flow;
lstLocations.TextAlign = TextAlign.Right;
lstLocations.CssClass = "CheckBoxList";
if (myReader.HasRows)
{
while (myReader.Read())
{
CheckBox cb = new CheckBox();
cb.ID = myReader[0].ToString();
cb.Text = myReader[1].ToString();
cb.AutoPostBack = false;
cb.CssClass = "CheckBox";
lstLocations.Items.Add(new ListItem(myReader[1].ToString(), myReader[0].ToString()));
lstLocations.Controls.Add(new LiteralControl("<br>"));
}
}
cn.Close();
myReader.Close();
}
And this is my selectedIndexChanged event:
protected void lstLocations_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
try
{
foreach (ListItem checkBox in lstLocations.Items)
{
if (checkBox.Selected == true)
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = true;
lblAfricaCountry.Visible = true;
}
}
else
{
value = checkBox.Text;
if (value == "Africa")
{
txtCountryOfAfrica.Visible = false;
lblAfricaCountry.Visible = false;
}
}
}
}
catch (Exception ex)
{
string msg = "Select Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
txtUser.Text = userName;
if (!IsPostBack)
{
ContainerDocumentation.ActiveTab = tabAddCustomer;
PopulateSector();
CreateRegionList();
PopulateOpportunitySource();
CreatelstProductGroupList();
PopulateStatus();
PopulateTenders();
PopulateOtherOpportunityType();
}
}
My guess: you are calling CreateRegionList in Page_Load without checking the IsPostBack property. That reloads all items from database and prevents this event from being triggered.
So check it:
protected bvoid Page_Load(Objject sender, EventArgs e)
{
if(!IsPostBack)
{
CreateRegionList();
}
}
That's because you have to set true to:
lstLocations.AutoPostBack = true;

asp.net gridview sorting and paging

the problem is if iam sorting with employee field assending or desending it is sorting perfectly if iam pressing next or previous button it is sorting assending order and displaying only in assending order can any body help tp how to bind gridview data at GridView1_PageIndexChanging() event to work perfectly
this is my default3.aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true"
AutoGenerateColumns="False" onsorting="GridView1_Sorting"
CurrentSortField="employeeid" CurrentSortDirection="ASC"
onrowcreated="GridView1_RowCreated" AllowPaging="true"
CaptionAlign="Bottom" onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender"
PageSize="2">
<Columns>
<asp:BoundField DataField="EmployeeId" HeaderText="Last Name"
ItemStyle-Width="15%" SortExpression="EmployeeId" >
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="First Name" ItemStyle-Width="15%"
SortExpression="Name" >
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="gender" HeaderText="Email" ItemStyle-Width="15%" >
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Change Password" ItemStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton ID="imgbtn1" runat="server">change password</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="15%"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="city" HeaderText="Date created" ItemStyle-Width="15%">
<ItemStyle Width="15%"></ItemStyle>
</asp:BoundField>
</Columns>
<PagerSettings Mode="NextPreviousFirstLast" />
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/images/up_arrow.png" Width="10px" />
</form>
</body>
</html>
this is my default.aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string gender { get; set; }
public string city { get; set; }
}
public static DataSet getallemployees()
{
String cs = "Data Source=.;database=users;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from tblEmployees", con);
SqlDataAdapter da = new SqlDataAdapter("select * from tblEmployees", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public static List<Employee> GetAllEmployees1(string sortColumn)
{
List<Employee> listEmployees = new List<Employee>();
String cs = "Data Source=.;database=users;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(cs))
{
string sqlQuery = "select * from tblEmployees";
if (!string.IsNullOrEmpty(sortColumn))
{
sqlQuery += " order by " + sortColumn;
}
con.Open();
SqlCommand cmd = new SqlCommand(sqlQuery, con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
employee.EmployeeId = Convert.ToInt32(rdr["Employeeid"]);
employee.Name = rdr["name"].ToString();
employee.Name = rdr["gender"].ToString();
employee.Name = rdr["city"].ToString();
listEmployees.Add(employee);
}
rdr.Close();
}
return listEmployees;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource= GetAllEmployees1("employeeid");
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SortDirection sortDirection = SortDirection.Ascending;
string sortField = string.Empty;
SortGridview(GridView1, e, out sortDirection, out sortField);
string strsortDirection = sortDirection == SortDirection.Ascending ? "ASC" : "DESC";
GridView1.DataSource = GetAllEmployees1(e.SortExpression + " " + strsortDirection);
GridView1.DataBind();
}
private void SortGridview(GridView gridview, GridViewSortEventArgs e, out SortDirection sortDirection, out string sortField)
{
sortField = e.SortExpression;
sortDirection = e.SortDirection;
if (gridview.Attributes["CurrentSortField"] != null && gridview.Attributes["CurrentSortDirection"] != null)
{
if (sortField == gridview.Attributes["CurrentSortField"])
{
if (gridview.Attributes["CurrentSortDirection"] == "ASC")
{
sortDirection = SortDirection.Descending;
}
else
{
sortDirection = SortDirection.Ascending;
}
}
gridview.Attributes["CurrentSortField"] = sortField;
gridview.Attributes["CurrentSortDirection"] = (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (GridView1.Attributes["CurrentSortField"] != null && GridView1.Attributes["CurrentSortDirection"] != null)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell tableCell in e.Row.Cells)
{
if (tableCell.HasControls())
{
LinkButton sortLinkButton = null;
if (tableCell.Controls[0] is LinkButton)
{
sortLinkButton = (LinkButton)tableCell.Controls[0];
}
if (sortLinkButton != null && GridView1.Attributes["CurrentSortField"] == sortLinkButton.CommandArgument)
{
Image image = new Image();
if (GridView1.Attributes["CurrentSortDirection"] == "ASC")
{
image.ImageUrl = "~/images/down_arrow.png";
image.Width = 10;
image.Height = 10;
}
else
{
image.ImageUrl = "~/images/~/images/up_arrow.png";
image.Width = 10;
image.Height = 10;
}
tableCell.Controls.Add(new LiteralControl(" "));
tableCell.Controls.Add(image);
}
}
}
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
Label1.Text = "Displaying Page " + (GridView1.PageIndex + 1).ToString() + " of " + GridView1.PageCount.ToString();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = getallemployees();
GridView1.DataBind();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class viewstate_dataset : System.Web.UI.Page
{
public DataSet getallemployees
{
get{
if (ViewState["Empdetails"] == null)
{
String cs = "Data Source=.;database=users;Integrated Security=SSPI";
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from tblEmployees", con);
SqlDataAdapter da = new SqlDataAdapter("select EmployeeId,Name,gender+','+Name as gender,city from tblEmployees", con);
DataSet ds = new DataSet();
da.Fill(ds);
ViewState["Empdetails"] = ds;
}
} return (DataSet)ViewState["Empdetails"];
}
set
{
ViewState["Empdetails"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = getallemployees;
GridView1.DataBind();
Session["sortDirection"] = SortDirection.Descending;
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortexp=e.SortExpression;
Session["sortexp"] = sortexp;
if (Session["sortDirection"] != null && Session["sortDirection"].ToString() == SortDirection.Descending.ToString())
{
Session["sortDirection"] = SortDirection.Ascending;
sort (sortexp, "ASC");
}
else
{
Session["sortDirection"] = SortDirection.Descending;
sort(sortexp, "DESC");
}
}
private void sort(string soreExpression, string p)
{
DataView dv = null;
dv = new DataView(getallemployees.Tables[0]);
dv.Sort = soreExpression + " " + p;
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string sortExp = string.Empty;
string NewSortDirection = string.Empty;
GridView1.PageIndex = e.NewPageIndex;
if (Session["sortexp"] != null)
{
sortExp = (string)Session["sortexp"];
if (Session["sortDirection"] != null && Session["sortDirection"].ToString() == SortDirection.Ascending.ToString())
{
NewSortDirection = "ASC";
}
else
{
NewSortDirection = "DESC";
}
sort(sortExp, NewSortDirection);
}
else
{
GridView1.DataSource = getallemployees;
GridView1.DataBind();
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (GridView1.Attributes["sortexp"] != null && Session["sortDirection"] != null)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell tableCell in e.Row.Cells)
{
if (tableCell.HasControls())
{
LinkButton sortLinkButton = null;
if (tableCell.Controls[0] is LinkButton)
{
sortLinkButton = (LinkButton)tableCell.Controls[0];
}
if (sortLinkButton != null && Session["sortexp"].ToString() == sortLinkButton.CommandArgument)
{
Image image = new Image();
if (Session["sortDirection"].ToString() == "ASC")
{
image.ImageUrl = "~/images/down_arrow.png";
image.Width = 10;
image.Height = 10;
}
else
{
image.ImageUrl = "~/images/up_arrow.png";
image.Width = 10;
image.Height = 10;
}
tableCell.Controls.Add(new LiteralControl(" "));
tableCell.Controls.Add(image);
}
}
}
}
}
}
}
but while sort data uparrow and down arrow is not coming on the header columns pls any body help me
The problem is you are calling getallemployees() on GridView1_PageIndexChanging function which ofcourse is returning unsorted data for next page.
In order to resolve this issue, you need to use ViewState for your data to be persistant.
Following solution will greatly help you out in sorting your grid using ViewState
http://www.stackoverflow.com/questions/702600/sorting-and-paging-with-gridview-asp-net?rq=1

ASP.NET GridView SortedAscendingHeaderStyle does not work

My SortedAscendingHeaderStyle and SortedDescendingHeaderStyle is not working at all
<asp:GridView ID="grdProducts" runat="server" CssClass="grid" AllowPaging="True" AllowSorting="True" PageSize="100" EmptyDataText="No data to show"
onrowdatabound="grdProducts_RowDataBound" onrowediting="grdProducts_RowEditing" onsorting="grdProducts_Sorting" AutoGenerateEditButton="True">
<AlternatingRowStyle CssClass="even" />
<SortedAscendingHeaderStyle ForeColor="White" CssClass="sorted" />
<SortedDescendingHeaderStyle CssClass="sorted desc" />
</asp:GridView>
Rows are sorted correctly when headers are clicked, but when I inspect the header using FireBug, it only shows: (this is when sorted ascending)
<th scope="col">
Namekey
</th>
ForeColor and CssClass are not set at all.
Anyone has any idea what I am doing wrong?
EDIT: My C# code behind
protected void grdProducts_Sorting(object sender, GridViewSortEventArgs e)
{
if ((string)ViewState["SortColumn"] == e.SortExpression)
ViewState["SortDirection"] = ((string)ViewState["SortDirection"] == "") ? " DESC" : "";
else
{
ViewState["SortColumn"] = e.SortExpression;
ViewState["SortDirection"] = "";
}
}
protected override void OnPreRender(EventArgs e)
{
BindGrid();
base.OnPreRender(e);
}
private void BindGrid()
{
string query = "SELECT ... ORDER BY " + ViewState["SortColumn"] + ViewState["SortDirection"];
DataTable dt = SqlFunctions.Select(query);
grdProducts.DataSource = dt;
grdProducts.DataBind();
}
I'm not sure if SortedDescendingHeaderStyle works without code if you're not using an asp:SQLDataSource as your GridView data source. But a little coding can get you there.
You need to apply the CSS style manually to the header cell. You can do it in the Sorting event.
protected void grdProducts_Sorting(object sender, GridViewSortEventArgs e)
{
if ((string)ViewState["SortColumn"] == e.SortExpression)
{
ViewState["SortDirection"] = ((string)ViewState["SortDirection"] == "") ? " DESC" : "";
grdProducts.HeaderRow.Cells[GetColumnIndex( e.SortExpression )].CssClass = "AscendingHeaderStyle";
}
else
{
ViewState["SortColumn"] = e.SortExpression;
ViewState["SortDirection"] = "";
grdProducts.HeaderRow.Cells[GetColumnIndex( e.SortExpression )].CssClass = "DescendingHeaderStyle";
}
BindGrid();
}
private int GetColumnIndex( string SortExpression )
{
int i = 0;
foreach( DataControlField c in gvwCustomers.Columns )
{
if( c.SortExpression == SortExpression )
break;
i++;
}
return i;
}
I don't have enough rep to comment on the accepted answer. When I tried applying the solution, it would sort properly, but did not apply the CSS class to what was eventually rendered.
In my case, invoking DataBind() on my grid AFTER sorting my DataSource (List) and assigning it as the grid's DataSource, but BEFORE setting the CssClass did the trick. Figured I'd share in case someone else encountered something similar.
I think it's the timing of your databinding. Change your databinding to work like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void grdProducts_Sorting(object sender, GridViewSortEventArgs e)
{
if ((string)ViewState["SortColumn"] == e.SortExpression)
ViewState["SortDirection"] = ((string)ViewState["SortDirection"] == "") ? " DESC" : "";
else
{
ViewState["SortColumn"] = e.SortExpression;
ViewState["SortDirection"] = "";
}
BindGrid();
}
GridView.Sorting Event
Super-late, but for reference. It works for me, using the following:
Here's my code (in x.aspx):
<asp:SqlDataSource ID="SqlDataSourceX" runat="server" ConnectionString="xxx"
EnableViewState="False" OnSelecting="SqlDataSourceXSelecting"></asp:SqlDataSource>
<asp:GridView ....
AllowSorting="True"
EnableSortingAndPagingCallbacks="False"
OnSorted="GridViewResults_OnSorted" .... DataSourceID="SqlDataSourceX" CssClass="table table-bordered text-left">
<SortedAscendingHeaderStyle CssClass="SortedAscendingHeaderStyle"></SortedAscendingHeaderStyle>
<SortedDescendingHeaderStyle CssClass="SortedDescendingHeaderStyle"></SortedDescendingHeaderStyle>
<Columns>
...
Here's my code (in x.aspx.cs):
protected void GridViewResults_OnSorted(object sender, EventArgs e) {
ExecuteSearch(); //Adds some where clauses to the SQL Data Source, no explicit sorting here
}
This then creates the following table headers, after clicking for sort:
<th class="SortedDescendingHeaderStyle" scope="col">
BUR Nummer
</th>

Sorting GridView Formed With Data Set

The following code sample is for sorting a GridView formed With a DataSet.
Source: http://www.highoncoding.com/Articles/176_Sorting_GridView_Manually_.aspx
But it is not displaying any output.
There is no problem in sql connection.
I am unable to trace the error, please help me.
Thank You.
public partial class _Default : System.Web.UI.Page
{
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
private DataSet GetData()
{
SqlConnection cnn = new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", cnn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
aspx page
asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting">
/asp:GridView>
Problem is with Page Load event when you fill the data you add it inside if(!IsPostBack) condition .
In this article, there is explained how to sort the GridView data in ASP.NET.
GridvIew control is a powerful data grid control that allows us to display the data in tabular format with sorting and pagination. It also allows us to manipulate the data as well.
http://www.dotnetfunda.com/articles/article1598-how-to-sort-the-gridview-data-in-aspnet.aspx
//Code Behind
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvbind();
}
}
protected DataSet gvbind() // Binding the gridview using Dataset and I am using stored procedure "Proc_Displayinfo"
{
con.Open();
SqlCommand command = new SqlCommand("Proc_Displayinfo", con);
SqlDataAdapter adpt = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adpt.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
return ds;
}
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void Gridview1_Sorting(object sender, GridViewSortEventArgs e)
{
gvbind();
DataTable dt = gvbind().Tables[0];
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
}
// Source Code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="StudentId" onsorting="Gridview1_Sorting" AllowSorting="True">
<asp:TemplateField HeaderText="StudentID" SortExpression="StudentID">
<ItemTemplate>
<asp:Label ID="LBLStudentID" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TXTStudentID" runat="server" Text='<%# Eval("StudentID") %>'></asp:TextBox>
</EditItemTemplate>

Resources