雖然下拉可以用SqlDataSource來處理,但如果下設定一些where條件式時,總覺得不方便,於是就自己手動打造會比較順手。
.aspx
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True">
<asp:ListItem Value="0">請選擇</asp:ListItem>
</asp:DropDownList>
.cs page_load
1 DropDownList1.DataSource = CreateSource("employee", "name,id", " where accoun");
2 DropDownList1.DataTextField = "name";
3 DropDownList1.DataValueField = "id";
4 DropDownList1.DataBind();
5 DropDownList1.Attributes.Add("onChange", "getList(this.value)");
2 DropDownList1.DataTextField = "name";
3 DropDownList1.DataValueField = "id";
4 DropDownList1.DataBind();
5 DropDownList1.Attributes.Add("onChange", "getList(this.value)");
function下面有一個自己寫的類別,當然自己改用為一般抓資料庫的方法就好了。
01 protected DataSet CreateSource(string strTableName, string field, string strWhere)
02 {
03 DBComm db = new DBComm();
04 DataSet ds = new DataSet();
05 db.TableName = strTableName;
06 db.WhereStmt = strWhere;
07 ds = db.GetDataSet(field, 0, 0, strTableName);
08 db.dbConn.Close();
09 db.Dispose();
10 db = null;
11 if (ds != null)
12 {
13 if (ds.Tables[0].Rows.Count <= 0)
14 {
15 return null;
16 }
17 else
18 {
19 return ds;
20 }
21 }
22 else
23 {
24 return null;
25 }
26 }
02 {
03 DBComm db = new DBComm();
04 DataSet ds = new DataSet();
05 db.TableName = strTableName;
06 db.WhereStmt = strWhere;
07 ds = db.GetDataSet(field, 0, 0, strTableName);
08 db.dbConn.Close();
09 db.Dispose();
10 db = null;
11 if (ds != null)
12 {
13 if (ds.Tables[0].Rows.Count <= 0)
14 {
15 return null;
16 }
17 else
18 {
19 return ds;
20 }
21 }
22 else
23 {
24 return null;
25 }
26 }
後面如果還要設定預設的值,可採用下面快速的方法:
1 ListItem li = this.DropDownList1.Items.FindByValue(dr["id"].ToString());
2 if (li != null) { li.Selected = true; }
2 if (li != null) { li.Selected = true; }