天天看点

DropDownList控件之使用技巧

开发中经常会遇到这样的问题,就是利用下拉列表框来进行数据绑定显示,以供用户选择使用。

在绑定中我们通常会为绑定后的第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"); //这是是设置背景颜色的

这样就可以达到想要的效果了。