关于gridview排序问题

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True" OnSorting="GridView1_Sorting">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="NAME" SortExpression="name" />
<asp:BoundField DataField="age" HeaderText="AGE" SortExpression="age" />
</Columns>
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
需要对GridView启用AllowSorting、设置OnSorting事件,对需要排序的列设定SortExpression属性。

// 正确的属性设置方法
            this.GridView1.Attributes.Add("SortExpression", "id");
this.GridView1.Attributes.Add("SortDirection", "ASC");

/// <summary>
/// GridView排序事件
/// </summary>
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
// 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();
// 假定为排序方向为“顺序”
        string sortDirection = "ASC";
// “ASC”与事件参数获取到的排序方向进行比较,进行GridView排序方向参数的修改
        if (sortExpression == this.GridView1.Attributes["SortExpression"])
{
//获得下一次的排序状态
            sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
}
// 重新设定GridView排序数据列及排序方向
        this.GridView1.Attributes["SortExpression"] = sortExpression;
this.GridView1.Attributes["SortDirection"] = sortDirection;
this.BindGridView();
}

/// 绑定到GridView
/// </summary>
    private void BindGridView()
{
// 获取GridView排序数据列及排序方向
        string sortExpression = this.GridView1.Attributes["SortExpression"];
string sortDirection = this.GridView1.Attributes["SortDirection"];
// 调用业务数据获取方法
        DataTable dtBind = this.getDB();
// 根据GridView排序数据列及排序方向设置显示的默认数据视图
        if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
{
dtBind.DefaultView.Sort
= string.Format("{0} {1}", sortExpression, sortDirection);
}
// GridView绑定并显示数据
        this.GridView1.DataSource = dtBind;
this.GridView1.DataBind();
}

为了减少数据库的链接,这里使用的缓存catche,将生成的ds放到catche里,然后重新绑定gridview。

转载于:https://www.cnblogs.com/lwt2005qq/archive/2011/06/15/2081248.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值