0

我有一个包含 3 个向导步骤的表单,当我单击按钮以动态添加文本框时,效果很好,但是当我进入下一步并单击添加以添加更多文本框时,它会自动添加所有文本前面步骤中的框,然后如果我继续单击它,则继续添加。

我如何防止这种情况发生。

私有列表 ControlsList { get { if (ViewState["controls"] == null) { ViewState["controls"] = new List(); } 返回(列表)视图状态[“控件”];} }

private int NextID
{
    get
    {
        return ControlsList.Count + 1;
    }
}


protected override void LoadViewState(object savedState)
{

    string section = Wizard1.ActiveStep.ID;
    int sectionNum = Wizard1.ActiveStepIndex;

    var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;

    base.LoadViewState(savedState);

    int count = 0;
    foreach (string txtID in ControlsList)
    {
        if (count == 0)
        {
            control.Controls.Add(new LiteralControl("<tr>"));
        }
        TextBox txt = new TextBox();
        control.Controls.Add(new LiteralControl("<td>"));
        txt.ID = txtID;
        control.Controls.Add(txt);
        control.Controls.Add(new LiteralControl("</td>"));

        count = count + 1;
        if (count == 3)
        {
            control.Controls.Add(new LiteralControl("</tr>"));
            count = 0;
        }

    }
}


protected void AddControlButton_Click(object sender, EventArgs e)
{


    string section = Wizard1.ActiveStep.ID;
    int sectionNum = Wizard1.ActiveStepIndex;

    var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;

    TextBox txt1 = new TextBox();
    TextBox txt2 = new TextBox();
    TextBox txt3 = new TextBox();


    txt1.ID = section.ToString() + "Size" + NextID.ToString();
    control.Controls.Add(new LiteralControl("<td>"));
    control.Controls.Add(txt1);
    control.Controls.Add(new LiteralControl("</td>"));
    ControlsList.Add(txt1.ID);

    txt2.ID = section.ToString() + "Description" + NextID.ToString();
    control.Controls.Add(new LiteralControl("<td>"));
    control.Controls.Add(txt2);
    control.Controls.Add(new LiteralControl("</td>"));
    ControlsList.Add(txt2.ID);

    txt3.ID = section.ToString() + "Quantity" + NextID.ToString();
    control.Controls.Add(new LiteralControl("<td>"));
    control.Controls.Add(txt3);
    control.Controls.Add(new LiteralControl("</td></tr>"));
    ControlsList.Add(txt3.ID);

}

4

1 回答 1

0

您将所有动态文本框存储在其中ViewState,然后ControlsList属性 getter 在构建文本框时返回整个列表。

我的建议是使用Sessioncache 而不是ViewState,因为它可以让您将文本框控件与每个向导步骤区分开来,如下所示:

Session["WizardStep1"] = listOfTextBoxesFromStep1;
Session["WizardStep2"] = listOfTextBoxesFromStep2;
Session["WizardStep3"] = listOfTextBoxesFromStep3;
于 2013-07-18T01:23:12.827 回答