如何防止在asp.net中添加两个列表?

时间:2013-10-28 22:48:32

标签: asp.net webforms

如何防止添加两个控件或列表?我已经尝试过这段代码,但它不起作用...... Pease帮助!

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        ViewState["check"] = "First_Time";
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    if (ViewState["check"] == "First_Time")
    {

        for (int i = 0; i < 6; i++)
        {
            CheckBoxList1.Items.Add(i.ToString());
        }
        ViewState["check"] = "Scond_Time";
    }
    else
    {
        Response.Write("Sorry, Can't create a list on second time");
    }
}

1 个答案:

答案 0 :(得分:1)

您的方法存在的问题是在回发时触发了按钮点击事件,因此您在Page_Load中的回发检查毫无意义。

由于CheckBoxList.Items默认存储在Viewstate中(它实现IStateManager),为什么不直接检查项目是否已添加?

protected void Button1_Click(object sender, EventArgs e)
{
    if (CheckBoxList1.Items.Count < 6)
    {
        CheckBoxList1.Items.Clear();
        for (int i = 0; i < 6; i++)
        {
            CheckBoxList1.Items.Add(i.ToString());
        }
    }
    else
    {
        // don't use Response.Write to output messages but controls
        Response.Write("Sorry, Can't create a list on second time");
    }
}