请大家帮我把这个程序的逻辑检查一下,到底是哪里出错了?我实在想不通,
功能描述:
<1> 第一次加载页面时点击按钮;则列表框有两个可先项 "男,女 ",如果选择
"男 "列表框则会变为 "第一,第二 "两个选项,此时如果选择 "第一 ",则此时
列表框变为 "男,女 "两个选项,也就是说按照这样的逻辑来显示列表框选项.
但是为什么问题,显示 "男,女 "两个选项呢?请大家帮我一下,谢谢了.
public partial class _Default : System.Web.UI.Page
{
SortedList s;
SortedList p;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DropDownList2.AutoPostBack = true;
s = new SortedList();
s.Add( "男 ", 1);
s.Add( "女 ", 2);
s.TrimToSize();
p = new SortedList();
p.Add( "第一 ", "one ");
p.Add( "第二 ", "two ");
p.TrimToSize();
DropDownList2.DataSource = s;
DropDownList2.DataTextField = "key ";
DropDownList2.DataValueField = "value ";
DropDownList2.DataBind();
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList2.SelectedItem.Text == "男 ")
{
DropDownList2.DataSource = p;
DropDownList2.DataTextField = "key ";
DropDownList2.DataValueField = "value ";
DropDownList2.DataBind();
DropDownList2.AutoPostBack = true;
}
if (DropDownList2.SelectedItem.Text == "第一 ")
{
DropDownList2.DataSource = s;
DropDownList2.DataTextField = "key ";
DropDownList2.DataValueField = "value ";
DropDownList2.DataBind();
DropDownList2.AutoPostBack = true;
}
Response.Write(DropDownList2.SelectedItem.Text + " <br> ");
Response.Write(DropDownList2.SelectedItem.Value + " <br> ");
}
}
[解决办法]
用 session 记录状态
如果测试着玩的话静态变量也可以
[解决办法]
晕,上午不是说了吗?你postback后,页面回到了初始状态。不信你看看。p和s都是null。
这样改
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList2.SelectedItem.Text == "男 ")
{
p = new SortedList();
p.Add( "第一 ", "one ");
p.Add( "第二 ", "two ");
p.TrimToSize();
DropDownList2.DataSource = p;
DropDownList2.DataTextField = "key ";
DropDownList2.DataValueField = "value ";
DropDownList2.DataBind();
DropDownList2.AutoPostBack = true;
}
else if (DropDownList2.SelectedItem.Text == "第一 ")
{
s = new SortedList();
s.Add( "男 ", 1);
s.Add( "女 ", 2);
s.TrimToSize();
DropDownList2.DataSource = s;
DropDownList2.DataTextField = "key ";
DropDownList2.DataValueField = "value ";
DropDownList2.DataBind();
DropDownList2.AutoPostBack = true;
}
Response.Write(DropDownList2.SelectedItem.Text + " <br> ");
Response.Write(DropDownList2.SelectedItem.Value + " <br> ");
}