转自:https://my.oschina.net/u/1441493/blog/193756
aspx文件:
<%@ 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文件
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();
}
}
转载请注明:懒人档案室 » 从sql中取数据并且绑定到 gridView