0

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

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");
    }
}
4

1 回答 1

1

您的方法的问题是按钮单击事件是在回发时触发的,因此您的回发签入Page_Load毫无意义。

由于默认情况下CheckBoxList.Items存储在其中(它实现),您为什么不简单地检查项目是否已添加?ViewstateIStateManager

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");
    }
}
于 2013-10-28T22:57:23.143 回答