開發中經常會遇到這樣的問題,就是利用下拉清單框來進行資料綁定顯示,以供使用者選擇使用。
在綁定中我們通常會為綁定後的第0個位置添加一個類似與"--請選擇--"之類的提示項。
在擷取一個DataSet對象後,可以為DropDownList控件進行綁定,綁定語句如下:
DataSet ds = DM.getDataSet(strSQL);
...
this.ddlCountry.DataTextField = "CountryName";
this.ddlCountry.DataValueField = "CountryID";
this.ddlCountry.DataSource = ds;
this.ddlCountry.DataBind();
this.ddlCountry.Items.Insert(0,"--請選擇--");
這裡為了代碼複用,可以對以上的DropDownList控件的綁定提取出一個方法來,比如說BindDropDownList()
private void BindDropDownList()
{
...
DataSet ds = DM.getDataSet(strSQL);
...
this.ddlCountry.DataTextField = "CountryName";
this.ddlCountry.DataValueField = "CountryID";
this.ddlCountry.DataSource = ds;
this.ddlCountry.DataBind();
this.ddlCountry.Items.Insert(0,"--請選擇--");
}
在編輯頁面中,當從資料庫中取得資料後,在下拉清單框中要讓被選中的項值要是從資料庫中取出的值,怎麼做呢?
首先根據擷取的一行資料集DataSet的對象來分别獲得各個字段的值,然後進行指派
DataSet ds = DM.getDataSet(strSQL);
foreach(DataRowView drv in ds.Tables[0].DefaultView)
...
//其它字段的綁定
...
//調用DropDownList控件綁定方法
BindDropDownList();
this.ddlCountry.Items.FindByText(drv["CountryName"].ToString()).Selected = true;
//一個小技巧,讓被選中的項字型發生改變
this.ddlGFLX.SelectedItem.Attributes.Add("style", "color: red");
this.ddlGFLX.SelectedItem.Attributes.Add("style", "background-color: red"); //這是是設定背景顔色的
這樣就可以達到想要的效果了。