GridView技巧之双向动态排序

<textarea cols="50" rows="15" name="code" class="c-sharp">using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection sqlcon; SqlCommand sqlcom; string strCon = "Data Source=(local);Database=AngelGarden;Uid=Angel;Pwd=Angel2008"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ViewState["SortOrder"] = "Name"; ViewState["OrderDire"] = "ASC"; BindGridView(); } } //设置数据源,绑定表结构 public void BindGridView() { string sqlstr = "SELECT * FROM AngelHome"; sqlcon = new SqlConnection(strCon); SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); DataSet myds = new DataSet(); sqlcon.Open(); myda.Fill(myds, "AngelHome"); DataView View = myds.Tables["AngelHome"].DefaultView; string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"]; View.Sort = sort; GridViewAngel.DataSource = View; GridViewAngel.DataKeyNames = new string[] { "ID" };//主键(定义主键,行操作事件使用) GridViewAngel.DataBind(); sqlcon.Close(); } //排序事件处理例程 protected void GridViewAngel_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;//安装点击的字段排序 } BindGridView(); } } 后台代码: &lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="AngelHome.aspx.cs" Inherits="_Default" %&gt; &lt;head runat="server"&gt; &lt;title&gt;GridView绝技 AngelGarden http://hi.baidu.com/diudiu_mei&lt;/title&gt; &lt;mce:style type="text/css"&gt;&lt;!-- @import url("AngelStyle.css"); --&gt;&lt;/mce:style&gt;&lt;style type="text/css" mce_bogus="1"&gt; @import url("AngelStyle.css");&lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;asp:GridView ID="GridViewAngel" runat="server" Width="500px" CssClass="GView_BodyCSS" PageSize="5" AutoGenerateColumns="False" &hellip;&hellip; OnSorting="GridViewAngel_Sorting" AllowSorting="True"&gt; &lt;HeaderStyle CssClass="GView_HeaderCSS"/&gt; &lt;Columns&gt; &lt;asp:ButtonField DataTextField="Name" HeaderText="名字" Text="按钮" SortExpression="Name" /&gt; &lt;asp:BoundField DataField="Gender" HeaderText="性别" SortExpression="Gender" /&gt; &lt;asp:BoundField DataField="Tel" HeaderText="联系方式" SortExpression="Tel" /&gt; &lt;asp:BoundField DataField="Address" HeaderText="家庭地址" SortExpression="Address" /&gt; &hellip;&hellip; &lt;/Columns&gt; &lt;RowStyle CssClass="GView_ItemCSS" /&gt; &lt;AlternatingRowStyle CssClass="GView_AlternatingItemCSS" /&gt; &hellip;&hellip; 实现排序GridView的设置,需要允许排序AllowSorting,并且设置各个字段的SortExpression,订阅排序过程:GridViewAngel_Sorting </textarea>

你可能感兴趣的:(GridView技巧之双向动态排序)