2012年3月9日 星期五

[GridView][DropDownList][ASP.NET] DropDownList in GridView

許多時候我們會在 GridView 搭配 DropDownList 來顯示資料,或是做 CRUD 的操作,
感念自己曾經也菜過XD(雖然現在菜味還是很重),寫個簡單的範例,提供給網友推敲的空間。

同樣搭配 北風資料庫
版面配置:
2011-07-08_142013

aspx
2011-07-08_142122


aspx.cs
01.protected void Page_Load(object sender, EventArgs e) {
02.if (!Page.IsPostBack) {
03.GridView1.DataSource = this.GetData();
04.GridView1.DataBind();
05.}
06.}
07. 
08./// <summary>
09./// 取得資料表。
10./// </summary>
11./// <returns></returns>
12.private DataTable GetData() {
13.DataTable result = new DataTable();
14.string connstring = @"Data Source=xxx\SQL2005;Initial Catalog=Northwind;User ID=yy;Password=kk";
15.using (SqlConnection conn = new SqlConnection(connstring)) {
16.using (SqlCommand cmd = new SqlCommand()) {
17.conn.Open();
18.cmd.Connection = conn;
19.cmd.CommandType = CommandType.Text;
20.cmd.CommandText = @"Select Top 15 * from Products";
21.SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
22.result = new DataTable();
23.result.Load(reader);
24.}
25.}
26.return result;
27.}
28. 
29.protected DataTable GetData_DropDownList() {
30.DataTable result = new DataTable();
31.string connstring = @"Data Source=xxx\SQL2005;Initial Catalog=Northwind;User ID=yy;Password=kk";
32.using (SqlConnection conn = new SqlConnection(connstring)) {
33.using (SqlCommand cmd = new SqlCommand()) {
34.conn.Open();
35.cmd.Connection = conn;
36.cmd.CommandType = CommandType.Text;
37.cmd.CommandText = @"Select CategoryID,CategoryName from Categories";
38.SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
39.result = new DataTable();
40.result.Load(reader);
41.}
42.}
43.return result;
44.}

結果參考
2011-07-08_142437

沒有留言:

張貼留言