【问题标题】:Gridview sorting when databinding from codebehind file从文件后面的代码绑定数据时的Gridview排序
【发布时间】:2014-02-04 05:01:50
【问题描述】:

我在几个页面上使用 asp.net web-form 和 gridview 来显示数据。我从代码隐藏文件中绑定 gridview。

到目前为止,我能够使用以下代码将数据源绑定到 gridview 并启用分页,但我面临的问题是在同一个网格上启用排序。关于如何启用分页以使其与以下代码一起使用的任何要点或帮助。

我还有一些附加字段,这些字段不属于此代码的一部分,我将其用于附加功能 onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand"

.ASPX 文件

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID" 
           Width="990px" BackColor="White" BorderColor="WhiteSmoke" BorderStyle="None" BorderWidth="0px" CellPadding="5" 
            Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black" GridLines="Horizontal" PageSize="10" CssClass="myheader"  AllowSorting="true" 
             onrowdatabound="GridView1_RowDataBound"  onrowcommand="GridView1_RowCommand" onpageindexchanging="GridView1_PageIndexChanging" >
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
                <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date"  DataFormatString="{0:yyyy/MM/dd}"/>
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <HeaderStyle  Height="32px" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" BorderStyle="None" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#242121" />
            <RowStyle   BorderColor="#f5f5f5" BorderStyle="Notset"/>
   </asp:GridView>

代码隐藏

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        GetDetails();
    }
}   


   protected void GetDetails()
{
    string strSql = "SELECT * FROM Test_Table Order by Date Desc ";
    DataSet ds = DataProvider.Connect_Select(strSql);
    GridView1.DataSource = ds;
    GridView1.DataBind();

}

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    GetDetails();
}

更新:代码更新为

.ASPX

OnSorting="GridView1_OnSorting"

代码隐藏

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
    string strSql = "SELECT * FROM Test_Table ";
    DataSet ds = DataProvider.Connect_Select(strSql);
    DataTable dataTable = ds.Tables[0];
    DataTable dataTable = ds.Tables[0];

    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " "+e.SortDirection;
        GridView1.DataSource = dataView;
        GridView1.DataBind();
    }
}

【问题讨论】:

  • &lt;PagerSettings PageButtonCount="8"&gt;&lt;/PagerSettings&gt;

标签: c# asp.net gridview webforms


【解决方案1】:

你应该像这样创建排序事件:

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
    {

        //TODO write tour code here to get data from database;
         DataTable dataTable = your datatable get from your db;

        if (dataTable != null)
        {
                if (e.SortDirection.ToString() == "Ascending")
                {
                    dataView.Sort = e.SortExpression + " ASC";
                }
                else if (e.SortDirection.ToString() == "Descending")
                {
                    dataView.Sort = e.SortExpression + " DESC";
                }

            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " "+e.SortDirection;
            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }


**e.SortExpression** provides sorting column name 

**e.SortDirection** provides sorting direction like ASC or DESC.

您也可以在页面的视图状态下选择排序方向

private string GridViewSortDirection
    {
        get { return ViewState["SortDirection"] as string ?? "DESC"; }
        set { ViewState["SortDirection"] = value; }
    }

private void SetSortDirection()
        {
            GridViewSortDirection = (GridViewSortDirection.ToUpper() == "DESC") ? "ASC" : "DESC";
        }

希望以上代码对你有所帮助。

【讨论】:

  • 我做了以下更改OnSorting="GridView1_OnSorting" 然后您的代码仍然无法正常工作..
  • 我用你的代码 sn-p 更新了我的问题,但它没有工作我做错了什么
  • Ditnt 出于某种原因工作,所以我发布的代码与您的代码几乎相似但略有不同..
  • OnSorting() 逻辑没有意义。您在第一次使用后定义了dataView。并且您已经在 if 语句中设置了一次 dataView.Sort(您还可以将 SortDirection 转换为字符串,而不是将其与 SortDirection.AscendingSortDirection.Descending 进行比较),然后在该条件语句下方再次设置 dataView.Sort .
【解决方案2】:

解决方案

我已经删除了旧代码,它有一个错误,因为当我们从一个页面来回移动到另一个页面时,排序无法正常工作。下面的代码是测试代码,可以很好地进行排序和分页。

public partial class _Default : System.Web.UI.Page
{

    string Sort_Direction = "Date DESC";

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
           // GetRegistrationDetails();
            ViewState["SortExpr"] = Sort_Direction;
            DataView dv = Getdata();
            GridView1.DataSource = dv;
            GridView1.DataBind();
        }
    }

    private DataView Getdata()
    {      
        string strSql = "SELECT * ROM TEST_Table ";
        DataSet ds = DataProvider.Connect_Select(strSql);
        DataView dv = ds.Tables[0].DefaultView;
        dv.Sort = ViewState["SortExpr"].ToString();
        return dv;
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        DataView dv = Getdata();
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
    {
        GridView1.PageIndex = 0;
        string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
        if (SortOrder[0] == e.SortExpression)
        {
            if (SortOrder[1] == "ASC")
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
            }
        }
        else
        {
            ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
        }
        GridView1.DataSource = Getdata();
        GridView1.DataBind();
    }
}

【讨论】:

  • @KnowledgeSeeker 此代码不会在PageIndexChanging 事件上保留排序表达式和排序方向。看我的回答。
  • @ekad,是的,你是对的。使用此代码,我可以对其他字段进行排序,但是如果我在第 3 页并且我对其进行排序,它仍然保留在该页面上,而它应该转到第一页...但是由于某种原因,您的代码不起作用(在您更新之前第三次代码)..我怎样才能在我的代码中解决这个问题..
  • 使用此代码我可以进行排序,但如果我在第 3 页并且我进行了新排序,它仍然保留在该页面上,而它应该转到第一页......仍然是错误的......
  • new sort 是什么意思?您使用的是您的代码还是我的代码?如果是我的代码,请在我的答案下方评论。
  • @ekad,我正在使用我的代码版本,我已经对其进行了进一步修改以使其正常工作......我将在 10 分钟内更新我的答案......因为我正在测试它......跨度>
【解决方案3】:

您已经为每一列设置了AllowSorting="true"SortExpression 属性,因此下一步是在回发之间保留最后一个排序表达式和排序方向,并在PageIndexChangingSorting 事件中使用它们。

我建议使用 ViewState 来保留最后的排序表达式和排序方向

private string SortExpression
{
    get
    {
        return ViewState["SortExpression"] == null ? string.Empty : ViewState["SortExpression"].ToString();
    }
    set
    {
        ViewState["SortExpression"] = value;
    }
}

private string SortDirection
{
    get
    {
        return ViewState["SortDirection"] == null ? string.Empty : ViewState["SortDirection"].ToString();
    }
    set
    {
        ViewState["SortDirection"] = value;
    }
}

这是获取下一个排序方向的方法:

private string GetSortDirection(string sortExpression)
{
    if (sortExpression == this.SortExpression)
    {
        // reverse the sort direction when current sort expression is the same as the last time
        if (this.SortDirection == "ASC")
        {
            return "DESC";
        }
        else
        {
            return "ASC";
        }
    }
    else
    {
        // always return ASC when current sort expression is different than the last time
        return "ASC";
    }
}

GetDetails方法需要知道排序表达式和排序方向,所以添加sortExpressionsortDirection参数:

protected void GetDetails(string sortExpression, string sortDirection)
{
    string strSql = string.Format("SELECT * FROM Test_Table Order by {0} {1}", sortExpression, sortDirection);

    DataSet ds = DataProvider.Connect_Select(strSql);
    GridView1.DataSource = ds;
    GridView1.DataBind();

    // save current sort expression and sort direction to ViewState
    this.SortExpression = sortExpression;
    this.SortDirection = sortDirection;
}

确保将OnSorting="GridView1_Sorting" 添加到GridView1 标记代码:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID" 
    Width="990px" BackColor="White" BorderColor="WhiteSmoke" BorderStyle="None" BorderWidth="0px" CellPadding="5" 
    Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black" GridLines="Horizontal" PageSize="10" CssClass="myheader"  AllowSorting="true" 
    OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" onpageindexchanging="GridView1_PageIndexChanging"
    OnSorting="GridView1_Sorting" >

假设默认排序表达式是Date,默认排序方向是DESC,这就是Page_LoadGridView1_PageIndexChangingGridView1_Sorting方法的样子

private const string DEFAULT_SORT_EXPRESSION = "Date";
private const string DEFAULT_SORT_DIRECTION = "DESC";

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GetDetails(DEFAULT_SORT_EXPRESSION, DEFAULT_SORT_DIRECTION);
    }
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;

    // use the last sort expression and sort direction
    GetDetails(this.SortExpression, this.SortDirection);
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    // get next sort direction
    string sortDirection = GetSortDirection(e.SortExpression);

    // get data with current sort expression and sort direction
    GetDetails(e.SortExpression, sortDirection);
}

更新

如果你想在排序的时候转到第1页,只需将GridView1.PageIndex = 0;添加到GridView1_Sorting即可:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    GridView1.PageIndex = 0;

    // get next sort direction
    string sortDirection = GetSortDirection(e.SortExpression);

    // get data with current sort expression and sort direction
    GetDetails(e.SortExpression, sortDirection);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    相关资源
    最近更新 更多