现在的位置: 首页 > 综合 > 正文

DataList中嵌套的DropDownList实现级联

2013年08月14日 ⁄ 综合 ⁄ 共 1594字 ⁄ 字号 评论关闭
HTML:

<asp:DataList ID="dlSubject" runat="server"> 
      
<ItemTemplate> 
          专业 
<asp:DropDownList ID="ddlMajor" runat="server" DataSource="<% BindMajor()%>" DataTextField="MajorName" DataValueField="MajorId" AutoPostBack="true"  OnSelectedIndexChanged="ddlMajor_SelectedIndexChanged" > 
            
</asp:DropDownList> 
          方向 
<asp:DropDownList ID="ddlDirection" runat="server" DataTextField="DirectionName" DataValueField="DirectionId"> 
              
</asp:DropDownList> 
          
</ItemTemplate>          
  
</asp:DataList> 

C#:

public DataSet bindMajor()
{
   
return new MajorBLL().SelectTheMajorByDeptID(Session["DeptID"].ToString()); //根据院系编号获取该院系的所有专业
}
//专业和专业下的方向都是放置在模板的DropDownList控件中,将DataList控件切换到模板状态下,双击专业的DropDownList控件,使其产生SelectedIndexChanged事件,在其HTML代码中已经看到。
protected void ddlMajor_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlMajor 
= (DropDownList)sender; //最重要的一句
        DropDownList ddlDirection = (DropDownList)ddlMajor.Parent.FindControl("ddlDirection");
        ddlDirection.DataSource 
= bindDirection(ddlMajor.SelectedValue);
        
//ddlDirection.DataTextField = "DirectionName";  //已经在HTML中设置过,就不需要再设置了
        
//ddlDirection.DataValueField = "DirectionId";
        ddlDirection.DataBind();
    }
public DataSet bindDirection(string p_strMajor)
    {
        
return new DirectionBLL().selectDirectionByMajor(p_strMajor); //根据专业编号获取属于该专业的所有方向
    }

本人认为用前一篇文章中提到过的给DataLIST控件中的某控件添加事件处理程序的方法也能实现DropDownList的级联,不过没有试验。
要在DataList控件的ItemDataBound事件中实现两个DropDownList的数据绑定初始化。
GridView控件中的级联也是类似的。GridView控件时在RowDataBound事件中实现两个DropDownList的数据绑定初始化。

抱歉!评论已关闭.