0

i have the following asp grid control:

            <asp:GridView ID="gwreportpub" CellPadding="5" AllowPaging="true" 
            runat="server" PageSize="15" OnPageIndexChanging="GridView1_PageIndexChanging" BackColor="White" Caption="" 
            AllowSorting="True" OnSorting="grdCause_Sorting" 
            BorderColor="MidnightBlue" 
            BorderStyle="Outset" Font-Size="Small" ForeColor="Navy" CssClass="mainBodyPosition" EnableSortingAndPagingCallbacks="True">

            <HeaderStyle BackColor="#E7E4DA" />

            <AlternatingRowStyle BackColor="#F8F6F0" />

            </asp:GridView>

this is the c# code behind, the table show but the sorting dose not work, why ??

 using System;
 using System.Collections;
 using System.Configuration;
 using System.Data;
 using System.Web;
 using System.Web.Security;

 public partial class ShowReportPub : System.Web.UI.Page 
 {  
    private DB_Utility dbu;
    protected double size = 1;
    private string connectionString;
    private OracleConnection connection;
    private OracleCommand processNumQuery;
    private int indexdropitem;
    private int coloreriga = 1;

    protected void Page_Load(object sender, EventArgs e)
         {


    if (!IsPostBack)
         {
        Session["CONNECTSTRING"] = Request["CONNECTSTRING"];

        if (Session["CONNECTSTRING"] == null)
        {
            Response.Redirect("sessionup.asp?type=ShowReportPub");
        }

        connectionString = Session["CONNECTSTRING"].ToString();

        if (connectionString.IndexOf("DSN=") >= 0)
        {
            Comuni.Utility util = new Utility();
            connectionString = util.ConnStr(connectionString);
            Session["CONNECTSTRING"] = connectionString;
        }
        connection = new OracleConnection(connectionString);
        connection.Open();
        dbu = new DB_Utility(Session["CONNECTSTRING"].ToString());

         }
         else
         {
        connectionString = Session["CONNECTSTRING"].ToString();
        if (connectionString.IndexOf("DSN=") >= 0)
        {
            Comuni.Utility util = new Utility();
            connectionString = util.ConnStr(connectionString);
            Session["CONNECTSTRING"] = connectionString;
        }
        connection = new OracleConnection(connectionString);
        connection.Open();
        dbu = new DB_Utility(Session["CONNECTSTRING"].ToString());
         }

    if (!IsPostBack)
    {
            //Response.Write("str :" + Request["param1"] + " - " + Request["param2"]);
            processNumQuery = new OracleCommand("select distinct nome_report from rpg_notification",connection);
            OracleDataReader reader = processNumQuery.ExecuteReader();

            while (reader.Read())
            {
                dropdownlist1.Items.Insert(0, new ListItem(reader.GetString(0), reader.GetString(0)));
            }
            reader.Close();

            //if(Request["param1"]!=""){
                //dropdownlist1.SelectedValue = Request["param1"];
            //}


    }
    if(Request["txtSchedDate"] == null)
    {

         //if(Request["param2"]!="")
            //txtSchedDate.Text = Request["param2"];
    }
    else
    {

         txtSchedDate.Text = Request["txtSchedDate"];
         gwreportpub.DataSource = getDatiFromDb();
         gwreportpub.DataBind();


    }

         }


    protected void Button1_Click(object sender, EventArgs e)
    {   
    string datarepo = "";
    if(Request["txtSchedDate"] != ""){
        DateTime schedDate = Convert.ToDateTime(Request["txtSchedDate"]);
        datarepo = schedDate.ToString("dd-MM-yyyy");
    }

    string reportname = dropdownlist1.SelectedItem.Text; 


    gwreportpub.DataSource = getDatiFromDb();
    gwreportpub.DataBind();
    gwreportpub.Visible = true;
    if (gwreportpub.Rows.Count == 0)
    {   
            tbnotif.Text = "Non vi sono report pubblicati";
            tbnotif.Visible = true;
    }
    else{
        tbnotif.Visible = true;
        tbnotif.Text = "Tabella dei Report Pubblicati: ";
    }
    return;


    }


    public DataSet getDatiFromDb()
    {
        DataSet dt;
        if(Request["txtSchedDate"] != ""){
            OracleDataAdapter adapter = new OracleDataAdapter();
            OracleCommand orclc = new OracleCommand("select relco, data_report, data_pubblicazione,anno_competenza, mese_competenza, pubblicato, md5, nome_file, path from rpg_notification where pubblicato = :flag and data_report <= TO_DATE(:repdate,'DD/MM/YYYY') and nome_report = :nome order by data_pubblicazione desc ",this.connection);
            orclc.Parameters.Add(new OracleParameter(":flag", OracleType.VarChar));
            orclc.Parameters.Add(new OracleParameter(":nome", OracleType.VarChar));
            orclc.Parameters.Add(new OracleParameter(":repdate", OracleType.VarChar));
            orclc.Parameters[":flag"].Value = "Y";
            orclc.Parameters[":nome"].Value = dropdownlist1.SelectedItem.Text;
            orclc.Parameters[":repdate"].Value = Request["txtSchedDate"].ToString();

            adapter.SelectCommand = orclc;

            dt = new DataSet("rpg_notification");   
            adapter.Fill(dt,"rpg_notification");
        }
        else{
            OracleDataAdapter adapter = new OracleDataAdapter();
            OracleCommand orclc = new OracleCommand("select relco, data_report, data_pubblicazione,anno_competenza, mese_competenza, pubblicato, md5, nome_file, path from rpg_notification where pubblicato = :flag and nome_report = :nome order by data_pubblicazione desc ",this.connection);
            orclc.Parameters.Add(new OracleParameter(":flag", OracleType.VarChar));
            orclc.Parameters.Add(new OracleParameter(":nome", OracleType.VarChar));
            orclc.Parameters[":flag"].Value = "E";
            orclc.Parameters[":nome"].Value = dropdownlist1.SelectedItem.Text;

            adapter.SelectCommand = orclc;

            dt = new DataSet("rpg_notification");   
            adapter.Fill(dt,"rpg_notification");
        }
        return dt;
    }
     protected void GridView1_PageIndexChanging(object sender,
     GridViewPageEventArgs e)
     {
         gwreportpub.PageIndex = e.NewPageIndex;
         gwreportpub.DataBind();
     }


 protected void grdCause_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
    gwreportpub.DataSource = getDatiFromDb().Tables[0];
    gwreportpub.DataBind();
    DataTable dt = gwreportpub.DataSource as DataTable;
    DataView dv = new DataView(dt);
    dv.Sort = sortExpression + direction;

    gwreportpub.DataSource = dv;
    gwreportpub.DataBind();

}
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";

public SortDirection GridViewSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null)
            ViewState["sortDirection"] = SortDirection.Ascending;

        return (SortDirection)ViewState["sortDirection"];
    }
    set { ViewState["sortDirection"] = value;
    }
}

}

4
  • Brian: "[...]Avoid trivial, tiny one-letter edits unless absolutely necessary." :) Commented Feb 11, 2013 at 14:30
  • please any help ??? i can't make it work :( Commented Feb 11, 2013 at 16:44
  • why e.SortExpression is empty?? Commented Feb 11, 2013 at 18:40
  • i did answer alone, thx to everyone! Commented Feb 12, 2013 at 9:01

2 Answers 2

1

ok the answer is this:

i had to change the control in this way:

            <asp:GridView ID="gwreportpub" CellPadding="5" AllowPaging="true" OnRowDataBound="gvdetails_RowDataBound" 
            runat="server" PageSize="15" OnPageIndexChanging="GridView1_PageIndexChanging" BackColor="White" Caption="" 
            AllowSorting="True" OnSorting="SortRecords" 
            BorderColor="MidnightBlue" autogeneratecolumns = "False"
            BorderStyle="Outset" Font-Size="Small" ForeColor="Navy" CssClass="mainBodyPosition" EnableSortingAndPagingCallbacks="False">

            <HeaderStyle BackColor="#E7E4DA" />

            <AlternatingRowStyle BackColor="#F8F6F0" />
            <columns>
                <asp:boundfield datafield="societa_di_vendita" headertext="Societa di vendita"  sortexpression="societa_di_vendita" />
                <asp:boundfield datafield="data_report" headertext="Data report" sortexpression="data_report" />
                <asp:boundfield datafield="data_pubblicazione" headertext="Data di pubblicazione" sortexpression="data_pubblicazione" />
                <asp:boundfield datafield="anno_competenza" headertext="Anno di competenza" sortexpression="anno_competenza" />
                <asp:boundfield datafield="mese_competenza" headertext="Mese di competenza" sortexpression="mese_competenza" />
                <asp:boundfield datafield="pubblicato" headertext="Pubblicato" sortexpression="pubblicato" />
                <asp:boundfield datafield="err_pubblicazione" headertext="Errore di pubblicazione" sortexpression="err_pubblicazione" />
                <asp:boundfield datafield="md5" headertext="Md5" sortexpression="md5" />
                <asp:boundfield datafield="nome_file" headertext="Nome del file" sortexpression="nome_file" />
                <asp:boundfield datafield="path" headertext="Percorso" sortexpression="Percorso" />
           </columns>
            </asp:GridView>

pay attention to the autogeneratecolumns = "False" and to the columns, sorting names

after this i have used this 2 functions :

    public SortDirection SortDirection
{
get
{
    if (ViewState["SortDirection"] == null)
    {
        ViewState["SortDirection"] = SortDirection.Ascending;
    }
    return (SortDirection)ViewState["SortDirection"];
}
set
{
   ViewState["SortDirection"] = value;
}
}   

protected void SortRecords(object sender, GridViewSortEventArgs e)
{
  sortexpr = e.SortExpression;
  string direction = string.Empty;

  if (SortDirection == SortDirection.Ascending)
  {
      SortDirection = SortDirection.Descending;
      direction = " DESC";
  }
  else
  {
     SortDirection = SortDirection.Ascending;
     direction = " ASC";
  }
  //Response.Write("" + sortexpr +  " -.- " + direction);
  DataTable table = this.getDatiFromDb().Tables[0];
  table.DefaultView.Sort = sortexpr + direction;
  gwreportpub.DataSource = table;
  gwreportpub.DataBind();

}

everything works now.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

 protected void grdCause_Sorting(object sender, GridViewSortEventArgs e)
{
    string sortExpression = e.SortExpression;

    if (GridViewSortDirection == SortDirection.Ascending)
    {
        GridViewSortDirection = SortDirection.Descending;
        ViewState["sortExpr"] = sortExpression + DESCENDING;
    }
    else
    {
        GridViewSortDirection = SortDirection.Ascending;
        ViewState["sortExpr"] = sortExpression  + ASCENDING;
    }

    SortGridView();
}

and

private void SortGridView()
{
    //  You can cache the DataTable for improving performance
    gwreportpub.DataSource = getDatiFromDb().Tables[0];
    gwreportpub.DataBind();
    if(ViewState["sortExpr"] != null){
      DataTable dt = gwreportpub.DataSource as DataTable;
      DataView dv = new DataView(dt);
      dv.Sort = (string)ViewState["sortExpr"];
    gwreportpub.DataSource = dv;
    gwreportpub.DataBind();
    }


}

5 Comments

gwreportpub.DataSource = dv; dv is not declared where it is ?
thanks for the heads up :)! i forgot to put it inside the if statement
Put a breakpoint at the beginning of the if statement in the function SortGridView(). Does it go inside the if statement after?
e.SortExpression is empty why??
Inside your gridview, do you have any templateField or BoundField with the "SortExpression" attribute? It is needed in order to sort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.