动态添加文本框到动态添加的面板

本文关键字:动态 添加 文本 | 更新日期: 2023-09-27 18:17:53

我以编程方式将面板(我称之为面板块以便更好地理解)添加到另一个面板。每个块包含一个标题,一个用于向块添加文本框的按钮和一个起始文本框。

这是我用来添加文本框的事件:

/// <summary>
/// Adds a text box to the button's parent
/// </summary>
protected void AddLabel_Click(object sender, EventArgs e)
{
    Button senderButton = (Button)sender;
    string parentId = senderButton.ID.Replace("_button","");
    Panel parent = (Panel)FindControl(update_panel, parentId);
    parent.Controls.Add(new TextBox
    {
        CssClass = "form-control canvas-label",
        ID = parent.ID + "_label" + parent.Controls.OfType<TextBox>().Count<TextBox>()
    });
}

然而,每次我添加一个文本框,我刚刚创建的文本框就会被删除

编辑这就是我最终解决它的方法(感谢Don):

1)保留一个文本框列表
Dictionary<string, List<string>> BlocksLabels
{
    get
    {
        if (ViewState["BlockLabels"] == null)
            ViewState["BlockLabels"] = new Dictionary<string, List<string>>();
        return ViewState["BlockLabels"] as Dictionary<string, List<string>>;
    }
    set { ViewState["BlockLabels"] = value; }
}

2)在创建块的方法中(从Page_Load调用):

if (BlocksLabels.ContainsKey(block.ID))
{
    foreach (string label in BlocksLabels[block.ID])
        block.Controls.Add(new TextBox { ID = labelId });
}
else
{
    // Add one empty canvas label by default
    string labelId = block.ID + "_label0";
    BlocksLabels[block.ID] = new List<string>();
    BlocksLabels[block.ID].Add(labelId);
    block.Controls.Add(new TextBox { ID = labelId });
}

3)最后,如果添加了一个新的文本框

Button senderButton = (Button)sender;
string parentId = senderButton.ID.Replace("_button", "");
Panel targetBlock = (Panel)FindControl(update_panel, parentId);
string labelId = targetBlock.ID + "_label" + BlocksLabels[targetBlock.ID].Count;
BlocksLabels[targetBlock.ID].Add(labelId);
targetBlock.Controls.Add(new TextBox { ID = labelId });

动态添加文本框到动态添加的面板

. NET中,如果以编程方式创建控件,则需要在回发期间再次重新创建该控件。

因此,在您的情况下,解决方案是存储已创建控件的id列表,并在回发期间重新创建它们(最好是在页面加载事件中)。

这对于Page控件树与存储的视图状态对齐是必要的。

见下面的代码:

<asp:HiddenField runat="server" ID="hdnTbCnt" Value="0" />
<asp:Panel runat="server" ID="panel1">
</asp:Panel>
<asp:Button Text="Add TextBox" runat="server" OnClick="AddTextBox_Click" />

后台代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        int tbCnt = Convert.ToInt32(hdnTbCnt.Value);
        for (int i = 1; i <= tbCnt; i++)
        {
            var tb = new TextBox()
            {
                ID = string.Format("txt{0}", i)
            };
            panel1.Controls.Add(tb);
        }
    }
}
protected void AddTextBox_Click(object sender, EventArgs e)
{
    int tbCount = Convert.ToInt32(hdnTbCnt.Value);
    var tb = new TextBox()
    {
        ID = string.Format("txt{0}", tbCount + 1)
    };
    panel1.Controls.Add(tb);
    hdnTbCnt.Value = (tbCount + 1).ToString();
}