aspx文件:
html
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridviewsort.aspx.cs" Inherits="gridviewsort" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="cityGridView" runat="server" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" OnPageIndexChanging="cityGridView_PageIndexChanging" OnSelectedIndexChanged="cityGridView_SelectedIndexChanged" > <Columns> <asp:BoundField DataField="cityID" HeaderText="城市ID" SortExpression="cityID" /> <asp:BoundField DataField="cityName" HeaderText="城市名" SortExpression="cityName" /> <asp:BoundField DataField="proID" HeaderText="父ID" SortExpression="proID" /> </Columns> </asp:GridView> </div> </form> </body> </html>
cs文件
sql
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; public partial class gridviewsort : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ViewState["cityName"] = "cityName"; ViewState["cityID"] = "cityID"; gridViewBind(); } protected void cityGridView_PageIndexChanging(object sender, GridViewPageEventArgs e) { } protected void cityGridView_SelectedIndexChanged(object sender, EventArgs e) { } protected void gridViewBind() { /* * 創建數據庫鏈接 * 首先在頭部引入DATA包 * using System.Data; * using System.Data.SqlClient; */ SqlConnection dataBaseCon = new SqlConnection("server=ZHOU-COMPUTER;database=Test;UId=mike;password=a03060910"); //配置sql語句 string sqlStr = "select * from [dbo].[City]"; //實例化SqlDataAdapter sql數據適配器對象 SqlDataAdapter da = new SqlDataAdapter(sqlStr, dataBaseCon); //實例化 DataSet 數據集 這個數據集會綁定在gridview上 DataSet data = new DataSet(); //向數據集中fill(填入)數據 da填入data da.Fill(data,"table"); //將填好數據的數據集data 綁定到gridView空間上 this.cityGridView.DataSource = data; this.cityGridView.DataBind(); } }