許多時候我們會在 GridView 搭配 DropDownList 來顯示資料,或是做 CRUD 的操作,
感念自己曾經也菜過XD(雖然現在菜味還是很重),寫個簡單的範例,提供給網友推敲的空間。
同樣搭配 北風資料庫
版面配置:
aspx
aspx.cs
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { GridView1.DataSource = this.GetData(); GridView1.DataBind(); } } /// <summary> /// 取得資料表。 /// </summary> /// <returns></returns> private DataTable GetData() { DataTable result = new DataTable(); string connstring = @"Data Source=xxx\SQL2005;Initial Catalog=Northwind;User ID=yy;Password=kk"; using (SqlConnection conn = new SqlConnection(connstring)) { using (SqlCommand cmd = new SqlCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select Top 15 * from Products"; SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); result = new DataTable(); result.Load(reader); } } return result; } protected DataTable GetData_DropDownList() { DataTable result = new DataTable(); string connstring = @"Data Source=xxx\SQL2005;Initial Catalog=Northwind;User ID=yy;Password=kk"; using (SqlConnection conn = new SqlConnection(connstring)) { using (SqlCommand cmd = new SqlCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select CategoryID,CategoryName from Categories"; SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); result = new DataTable(); result.Load(reader); } } return result; }
0 Comments:
張貼留言