效果
注意:DropDownList 中AutoPostBack属性的值设置为Ture
.aspx
<form id="form1" runat="server">
<div style="text-align:center">
<asp:Label ID="lblYear" runat="server" Text="学年:"></asp:Label>
<asp:DropDownList ID="ddlYear" runat="server" OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" AutoPostBack="True" ></asp:DropDownList>
<asp:Label ID="lblTerm" runat="server" Text="学期:"></asp:Label>
<asp:DropDownList ID="ddlTerm" runat="server" OnSelectedIndexChanged="ddlTerm_SelectedIndexChanged" AutoPostBack="True" ></asp:DropDownList>
<asp:Label ID="lblCollege" runat="server" Text="分院:"></asp:Label>
<asp:DropDownList ID="ddlCollege" runat="server" OnSelectedIndexChanged="ddlCollege_SelectedIndexChanged" AutoPostBack="True" ></asp:DropDownList>
<asp:Label ID="lblTeacher" runat="server" Text="教师:"></asp:Label>
<asp:DropDownList ID="ddlTeacher" runat="server" OnSelectedIndexChanged="ddTeacher_SelectedIndexChanged" AutoPostBack="True" ></asp:DropDownList>
</div>
</form>
.aspx.cs
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindYear(); //调用自定义方法向"学年"下拉列表框填充列表项
BindTerm(); //调用自定义方法向"学期"下拉列表框填充列表项
BindCollege(); //调用自定义方法向"分院"下拉列表框填充列表项
BindTeacher(); //调用自定义方法向"教师"下拉列表框填充列表项
}
}
protected void BindYear()
{
ddlYear.Items.Clear(); // 清空学年下拉列表框
int startYear = DateTime.Now.Year - 10;
int currentYear = DateTime.Now.Year;
for (int i = startYear; i <= currentYear; i++) //向学年下拉列表添加项
{
ddlYear.Items.Add(new ListItem((i - 1).ToString() + "-")+i.ToString());
}
ddlYear.SelectedValue = (currentYear - 1).ToString() + "-" + currentYear.ToString();
}
protected void BindTerm()
{
ddlTerm.Items.Clear(); //清空学期下拉列表
for (int i = 1; i <= 2; i++)
{
ddlTerm.Items.Add(i.ToString());
}
}
protected void BindCollege()
{
ddlCollege.Items.Clear();
ddlCollege.Items.Add(new ListItem("计算机学院"));
ddlCollege.Items.Add(new ListItem("管理学院"));
ddlCollege.Items.Add(new ListItem("电子信息学院"));
}
protected void ddlCollege_SelectedIndexChanged(object sender, EventArgs e)
{
BindTeacher();
}
protected void BindTeacher()
{
ddlTeacher.Items.Clear();
switch(ddlCollege.SelectedValue) //根据不同学院添加不同的老师姓名
{
case "计算机学院": //在实际工程中添加的来源于数据库
ddlTeacher.Items.Add(new ListItem("马云"));
ddlTeacher.Items.Add(new ListItem("马化腾"));
ddlTeacher.Items.Add(new ListItem("超级玛丽"));
break;
case "管理学院":
ddlTeacher.Items.Add(new ListItem("李彦宏"));
ddlTeacher.Items.Add(new ListItem("李开复"));
break;
case "电子信息学院":
ddlTeacher.Items.Add(new ListItem("刘强东"));
ddlTeacher.Items.Add(new ListItem("蔡国庆"));
break;
}
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ddlTerm_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ddTeacher_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}