Hi,
I have problem using Paging and Sorting in ASP.Net GridView example Paging and Sorting in ASP.Net GridView example.
I don't have error in my code below, but the sorting not working.
Please help me
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" OnSorting="OnSorting"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
<Columns>
<asp:TemplateField HeaderText="Progr" SortExpression="Progr"
ItemStyle-CssClass="ddl_Class_new" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink ID="hlProgr" runat="server"
Text='<%# Eval("Progr") %>'
NavigateUrl='<%# (String.IsNullOrEmpty(Eval("Progr").ToString()) ? "" :
String.Format("sEdit.aspx?spID={0}&sp={1}",
MaP.Base64ForUrlEncode(Eval("pID").ToString().ToUpper()),
MaP.Base64ForUrlEncode(Eval("Progr").ToString().ToUpper())))%>'
onclick="javascript:w=window.open(this.href, 'pID',
'left=150,top=150,width=1800,height=1800,toolbar=0,resizable=0');
return false;"
CssClass="linkbutton">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData(string sortExpression = null)
{
gvProducts.DataSource = RetrieveProducts();
gvProducts.DataBind();
}
private string SortDirection
{
get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
set { ViewState["SortDirection"] = value; }
}
protected void OnSorting(object sender, GridViewSortEventArgs e)
{
BindData(e.SortExpression);
}
private DataSet RetrieveProducts(string sortExpression = null)
{
if (!String.IsNullOrEmpty(MaP.Container.tname))
{
DataTable dt = new DataTable();
DataSet ds = new DataSet();
using (MySqlConnection myConnectionString =
new MySqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (MySqlCommand cmd =
new MySqlCommand("sp_select_gv", myConnectionString))
{
cmd.CommandTimeout = 2147483;
cmd.Connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
MTparameters(cmd);
MySqlDataAdapter adapter =
new MySqlDataAdapter(cmd);
adapter.Fill(ds);
if (ds.Tables.Count > 0)
{
if (sortExpression != null)
{
DataView dv = dt.AsDataView();
this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
dv.Sort = sortExpression + " " + this.SortDirection;
gvProducts.DataSource = dv;
}
else
{
gvProducts.DataSource = dt;
}
dt = ds.Tables[0];
}
}
}
return ds;
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('No good');" +
"window.location='https://google.com';", true);
return null;
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
BindData();
}