標籤:級聯列表 asp.net 控制項 dropdownlist
今天我們來一起用ASP.net實現一個級聯,這個小不點應該是會經常用到的的。
咱們簡單的畫兩個表單。文字框會根據下拉框所選的內容顯示不同的內容。
具體實現效果如下
步驟一:
準備工作,建立相應的資料庫。
顯示效果如下
附指令碼如下
create database departmentuse departmentcreate table TDepartment( depID int primary key, depName varchar(30) not null)insert into TDepartment values(1,'教務')insert into TDepartment values(2,'高校')insert into TDepartment values(3,'辦公室')create table emp(empID int primary key,empName varchar(30) not null,depID int foreign key references TDepartment(depID))insert into emp values(1,'小馬',1)insert into emp values(2,'小丹',1)insert into emp values(3,'小妹',1)insert into emp values(4,'馬丹妹',3)
步驟二:
建立項目為 ASP.ne Web 表單應用程式。在表單中畫 圖中的兩個控制項。DropDownList 和ListBox,分別命名為 ddlDep 和lBoxEmp。同時將DropDownList中AutoPostBack屬性設定為TRUE(目的是讓每次重選列表能有響應)。
我們需要在formload 和ddlDep_SelectedIndexChanged 時間中編寫相應的代碼。其中ddlDep_SelectedIndexChanged是選中空間ddlDep在右側屬性-事件中雙擊時間SelectedIndexChanged
using System;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.SqlClient;//資料庫namespace department{ public partial class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.ListBox lBoxEmp; protected System.Web.UI.WebControls.DropDownList ddlDep; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { SqlConnection con = DBcon.createConnection(); con.Open(); //顯示部門 SqlCommand cmd = new SqlCommand("select * from TDepartment", con); SqlDataReader sdr = cmd.ExecuteReader(); this.ddlDep.DataSource = sdr; this.ddlDep.DataTextField = "depName"; this.ddlDep.DataValueField = "depID"; this.ddlDep.DataBind(); sdr.Close(); //顯示員工 SqlCommand cmdEmp = new SqlCommand("select * from emp where depID=" + this.ddlDep.SelectedValue, con); SqlDataReader sdrEmp = cmdEmp.ExecuteReader(); ; while (sdrEmp.Read()) { this.lBoxEmp.Items.Add(new ListItem(sdrEmp.GetString(1), sdrEmp.GetInt32(0).ToString())); } sdrEmp.Close(); //此處防止使用者代碼以初始化頁面 //關閉串連 con.Close(); } } protected void ddlDep_SelectedIndexChanged(object sender, EventArgs e) { this.lBoxEmp.Items.Clear(); SqlConnection con = DBcon.createConnection(); con.Open(); //顯示員工 SqlCommand cmdEmp = new SqlCommand("select * from emp where depID=" + this.ddlDep.SelectedValue, con); SqlDataReader sdrEmp = cmdEmp.ExecuteReader(); ; while (sdrEmp.Read()) { this.lBoxEmp.Items.Add(new ListItem(sdrEmp.GetString(1), sdrEmp.GetInt32(0).ToString())); } sdrEmp.Close(); //此處防止使用者代碼以初始化頁面 //關閉串連 con.Close(); } }}
以上是主要內容,下面把擷取資料庫的語句寫在下面。這樣便是一個完整的小功能。
using System;using System.Data.SqlClient;namespace department{ public class DBcon { public DBcon(){ } public static SqlConnection createConnection() { SqlConnection con = new SqlConnection("server=.;database=department;uid=sa;pwd=123456;"); return con; } }}
總結:
我們不斷的在學習每一個控制項的使用,一方面讓我們能更加靈活的運用其方法和特性,另一方面也讓我們更加熟悉每一種語言。雖然都是一小步一小步的去走,每每成功一個也還是感到喜悅。
ASP.net 控制項實現資料級聯