【问题标题】:asp.net GridView table does not sortasp.net GridView 表不排序
【发布时间】:2013-02-11 14:10:38
【问题描述】:

我有以下asp网格控件:

            <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>

这是后面的c#代码,表格显示但排序不起作用,为什么??

 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;
    }
}

}

【问题讨论】:

  • Brian:“[...]除非绝对必要,否则避免琐碎、微小的单字母编辑。” :)
  • 请帮忙???我不能让它工作:(
  • 为什么 e.SortExpression 是空的??
  • 我一个人回答,谢谢大家!

标签: c# asp.net sorting gridview


【解决方案1】:

好的,答案是这样的:

我必须以这种方式更改控件:

            <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>

注意 autogeneratecolumns = "False" 和列,排序名称

在这之后我使用了这两个功能:

    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();

}

现在一切正常。

【讨论】:

    【解决方案2】:

    试试这个:

     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();
    }
    

    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();
        }
    
    
    }
    

    【讨论】:

    • gwreportpub.DataSource = dv; dv 没有声明它在哪里?
    • 感谢您的提醒 :)!我忘了把它放在 if 语句中
    • 在函数SortGridView()的if语句的开头放一个断点。之后是否进入 if 语句?
    • e.SortExpression 为什么是空的??
    • 在您的gridview 中,您是否有任何带有“SortExpression”属性的templateField 或BoundField?它是排序所必需的。
    猜你喜欢
    • 2016-07-31
    • 2017-03-28
    • 2011-09-02
    • 2023-03-12
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    相关资源
    最近更新 更多