DropDownList 绑定及初始值问题

来源:互联网 发布:空军工程大学淘宝地址 编辑:程序博客网 时间:2024/05/16 18:48

很多人可能在DropDownList绑定数据源的时候存在一些问题。而本人以前在项目中碰到的问题就是GridView与DetailsView的二级联动的时候,编辑状态下,DropDownList默认选定的值显示错误。

 

下面是一种解决的办法:

 

 

在前台,DetailsView的一项模板项里面添加如下

        <asp:TemplateField HeaderText="所属分类:"  SortExpression="NewsCategoryID" ItemStyle-HorizontalAlign="Left">
            <EditItemTemplate>
                <asp:Label ID="NewsCategoryLabel" runat="server" Text='<%# Bind("NewsCategoryID") %>' Width="700" Visible="False"></asp:Label>
                <asp:DropDownList ID = "DropDownList1" runat="server"  Width="700"></asp:DropDownList>
            </EditItemTemplate>
  </asp:TemplateField>

 

大家看见那红色的绑定字段就是我们从表中查到的这个字段原始的值。我们假设NewsCategoryID可供选择的值有1、2、3、4、5。

分别对应幼儿园、小学、初中、高中、大学这么5个值。那如果我们通过GridView选定某一项得到的值是2,也就是对应的值是小学的话,那么在DetailsView里面的存在的下拉框DropDownList1默认的值也应该是2。那么在绑定的时候如何保证默认的值是2呢?大家都知道如果我们查找NewsCategoryID可供的选值是有1、2、3、4、5.就算绑定了那么默认的选择值也是这个顺序的。我们接下来要做到的是选中DropDownList1默认的值2。

在后台,我们可以这么来写:

    protected void DetailsView_DataBound(object sender, EventArgs e)
    {

      //编辑
        if (DetailsView.CurrentMode == DetailsViewMode.Edit)
        {
            Label lab8 = (Label)DetailsView.Rows[9].Cells[1].FindControl("NewsCategoryLabel");
            string NewsCategoryID, NewsCategoryName;

            //遍历DropDownList1控件,获得所有NewsCategory
            DropDownList DDL_Category = (DropDownList)DetailsView.FindControl("DropDownList1");
            DataTable DT_Category = NewsAccess.GetNewsCategoryList();
            for (int i = 0; i < DT_Category.Rows.Count; i++)
            {
                NewsCategoryID = DT_Category.Rows[i]["NewsCategoryID"].ToString();
                NewsCategoryName = DT_Category.Rows[i]["NewsCategoryName"].ToString();
                DDL_Category.Items.Add(new ListItem(NewsCategoryName, NewsCategoryID));
            }           
            DDL_Category.SelectedValue = lab8.Text;

    }

后台的代码主要是在找到DropDownList1,并根据GetNewsCategoryList方法找到默认绑定的值(也就是1、2、3、4、5),当然绑定的方法有很简单,那么我这里是通过查找到TextValue属性的值,然后再通过Add方法分别添加进去。那么如何选定默认的值呢,主要是通过找到NewsCategoryLabel,并将他得值赋给DropDownList1SelectedValue 属性。也就是上面蓝色标注的最后一段代码。

注:上面前台里面有一个小技巧,NewsCategoryLabel保存了默认选定的值,但是Visible="False",不让其显示出来,这样既保存了要选定的值,又不影响界面的显示。

原创粉丝点击