1、效果图
2、前台代码
说明:红色代码为核心代码
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvData_RowDataBound" onsorting="gvData_Sorting" AllowSorting="true"> <Columns> <asp:TemplateField HeaderText="新闻标题"> <ItemTemplate> <asp:Label ID="labtitle" runat="server" Text=‘<%# Bind("title") %>‘></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="阅读量" SortExpression="count"> <ItemTemplate> <asp:Label ID="labcount" runat="server" Text=‘<%# Bind("count") %>‘></asp:Label> </ItemTemplate> <ItemStyle Width="15%" /> </asp:TemplateField> <asp:TemplateField HeaderText="添加人"> <ItemTemplate> <asp:Label ID="labadmin" runat="server" Text=‘<%# Bind("adminName") %>‘></asp:Label> </ItemTemplate> <ItemStyle Width="25%" /> </asp:TemplateField> <asp:TemplateField HeaderText="时间" SortExpression="ID"> <ItemTemplate> 添加:<asp:Label ID="labtime" runat="server" Text=‘<%# Bind("times") %>‘></asp:Label> <asp:Label ID="labtimepass" runat="server" Text=‘<%# Bind("timepass") %>‘></asp:Label> <br /> </ItemTemplate> <ItemStyle Width="30%" /> </asp:TemplateField> </Columns> </asp:GridView>
3、后台代码
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["SortOrder"] = "ID"; //默认排序字段,必须 ViewState["OrderDire"] = "Desc"; //默认排序,必须 fillData(); } } protected void fillData() { string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
string sql = “select * from dt_news ”+sort; //datatable 自己写,绑定GridView自己写,我这里就不写了
}
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e) { //判断是否是表头 if (e.Row.RowType == DataControlRowType.Header) { //判断是否进行排序 //是否是排序字段信息 for (int i = 0; i < e.Row.Cells.Count; i++) { ControlCollection cons= e.Row.Cells[i].Controls; if (cons.Count == 1) { LinkButton lb = cons[0] as LinkButton; if (lb != null) { if (ViewState["SortOrder"].ToString() == lb.CommandArgument) { if (ViewState["OrderDire"].ToString() == "Desc") { lb.Text += "▼"; } else { lb.Text += "▲"; } } } } } } }
protected void gvData_Sorting(object sender, GridViewSortEventArgs e) { string sPage = e.SortExpression; if (ViewState["SortOrder"].ToString() == sPage) { if (ViewState["OrderDire"].ToString() == "Desc") ViewState["OrderDire"] = "ASC"; else ViewState["OrderDire"] = "Desc"; } else { ViewState["SortOrder"] = e.SortExpression; } PageControl1.pageNow = 1; fillData(); }
时间: 2024-11-29 09:13:18