Sorting not working in the Gridview as Required

I tried the sorting functionality like below

<asp:GridView ID="grdUser" AllowPaging="true" AutoGenerateColumns="False" OnDataBound="grdUser_DataBound" OnRowDeleting="grdUser_RowDeleting" OnPreRender="PreRenderGrid" runat="server" Width="100%" border="1" DataKeyNames="Id" PageSize="10" EmptyDataText="No Records Found" OnPageIndexChanging="grdUser_PageIndexChanging" EnableSortingAndPagingCallbacks="false" CssClass="hoverTable" AllowSorting="true" OnSorting="grdUser_Sorting" ShowFooter="false" HeaderStyle-CssClass="k-grid td" OnRowCommand="grdUser_RowCommand"> <AlternatingRowStyle CssClass="k-alt" /> <Columns> <asp:TemplateField HeaderText="Select" ItemStyle-Width="5"> <ItemTemplate> <asp:CheckBox ID="chkDelete" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="username" HeaderText="Username" SortExpression="username" ItemStyle-Width="30" /> <asp:BoundField DataField="email" HeaderText="Email ID" SortExpression="email" ItemStyle-Width="30" /> <asp:BoundField DataField="ngoname" HeaderText="NGO Name" ItemStyle-Width="30" /> <asp:BoundField DataField="usertype" HeaderText="UserType" ItemStyle-Width="30" Visible="false" /> <asp:BoundField DataField="UserRoleName" HeaderText="User Role" ItemStyle-Width="30" /> <asp:BoundField DataField="active" HeaderText="Active" SortExpression="active" ItemStyle-Width="30" /> <asp:TemplateField HeaderText="Action" HeaderStyle-Width="5%"> <ItemTemplate> <asp:ImageButton ID="btnEdit" AlternateText="Edit" ImageUrl="~/images/edit.png" ToolTip="Edit" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" /> <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" ToolTip="Delete" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" /> </ItemTemplate> </asp:TemplateField> </Columns>

Also see my code behind:-

protected void grdUser_Sorting(object sender, GridViewSortEventArgs e) { DataTable dt = Session["tbl_User"] as DataTable; DataView dataView = new DataView(dt); dataView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression); grdUser.DataSource = dataView; grdUser.DataBind(); } private string GetSortDirection(string column) { string sortDirection = "ASC"; string sortExpression = ViewState["SortExpression"] as string; if (sortExpression != null) { if (sortExpression == column) { string lastDirection = ViewState["SortDirection"] as string; if ((lastDirection != null) && (lastDirection == "ASC")) { sortDirection = "DESC"; } } } ViewState["SortDirection"] = sortDirection; ViewState["SortExpression"] = column; return sortDirection; }

But when I debugged the code, I am always getting dt as null. Please help


Code for binding gridview:-

protected void BindGrid() { string username = string.Empty; string usertype = string.Empty; try { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString); SqlCommand cmd = new SqlCommand("SELECT usertype,username FROM tbl_User WHERE [email protected]", conn); cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = Session["User"].ToString(); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { if (dr.Read()) { username = dr["username"].ToString(); usertype = dr["usertype"].ToString(); } } conn.Close(); string query = string.Empty; if (!string.IsNullOrEmpty(usertype)) { if (usertype == "0") // superadmin { query = "select tbl_User.Id,tbl_ngoname.ngo_name, tbl_User.username,,tbl_User.usertype,,(CASE WHEN tbl_User.usertype='1' THEN 'Admin' WHEN tbl_User.usertype='0' THEN 'Super Admin' WHEN tbl_User.usertype='2' THEN 'User' END) AS UserRoleName FROM tbl_User INNER JOIN tbl_ngoname on tbl_ngoname.Id = tbl_User.NgoId ORDER By Id DESC"; } if (usertype == "1") // admin { query = "select tbl_User.Id,tbl_ngoname.ngo_name, tbl_User.username,,tbl_User.usertype,,(CASE WHEN usertype='1' THEN 'Admin' WHEN usertype='0' THEN 'Super Admin' WHEN usertype='2' THEN 'User' END) AS UserRoleName from tbl_User INNER JOIN tbl_ngoname on tbl_ngoname.Id = tbl_User.NgoId WHERE usertype != '0' ORDER By Id DESC"; } if (usertype == "2") // user { query = "select tbl_User.Id,tbl_ngoname.ngo_name, tbl_User.username,,tbl_User.usertype,,(CASE WHEN usertype='1' THEN 'Admin' WHEN usertype='0' THEN 'Super Admin' WHEN usertype='2' THEN 'User' END) AS UserRoleName from tbl_User INNER JOIN tbl_ngoname on tbl_ngoname.Id = tbl_User.NgoId WHERE username='" + username + "' ORDER By Id DESC"; } cmd = new SqlCommand(query, conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); grdUser.DataSource = ds.Tables[0]; grdUser.DataBind(); DisablePageDirections(); grdUser.BottomPagerRow.Visible = true; Session["tbl_User"] = ds.Tables[0]; } } catch (Exception) { throw; } }


private DataTable GetData(SqlCommand cmd) { DataTable dt = new DataTable(); SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString); SqlDataAdapter sda = new SqlDataAdapter(); cmd.Connection = conn; try { conn.Open(); sda.SelectCommand = cmd; sda.Fill(dt); return dt; } catch (Exception ex) { throw ex; } finally { conn.Close(); sda.Dispose(); conn.Dispose(); } }

-------------Problems Reply------------

You are setting session with name tbl_user on page load and when you get it you are getting with GridViewData.

On page load you set session with name tbl_user

Session["tbl_User"] = dt;

And you get it with name GridViewData

DataTable dt = Session["GridViewData"] as DataTable;

When you get the datatable from session in grdUser_Sorting change it like this

protected void grdUser_Sorting(object sender, GridViewSortEventArgs e)
//Retrieve the table from the session object.
DataTable dt = Session["tbl_user"] as DataTable;
if (dt != null)
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
grdUser.DataSource = Session["tbl_user"];

Category:c# Views:0 Time:2018-02-07

Related post

Copyright (C), All Rights Reserved.

processed in 0.155 (s). 11 q(s)