ASP.NET 动态创建控件和回发 [英] ASP.NET dynamically created controls and Postback

查看:34
本文介绍了ASP.NET 动态创建控件和回发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已被问过数千次,我之前也曾为此苦苦挣扎过,但由于某种原因,我无法完成我想要完成的任务...我有一个动态添加的 LinkBut​​ton,单击该按钮时将动态添加一个控件(在本例中为文本框)到同一个面板.目的是连续添加与单击 LinkBut​​ton 的次数一样多的控件(即我单击一次,一个框,然后再单击一次将给我 2 个框,另一次单击添加第三个).在下面的代码中,我使用序列化的当前日期和时间为每个文本框控件创建唯一 ID.

I know this question has been asked thousands of times, and I've struggled with it before, but for some reason, I can't accomplish what I want to accomplish... I have a dynamically added LinkButton that when clicked will dynamically add a control (in this example, a textbox) to the same panel. The intent is to continuously add on as many controls as times the LinkButton was clicked (i.e. I click it once, one box, then another click will give me 2 boxes, another click adds a 3rd). In the code below, I use the current date and time serialized to create a unique ID for each textbox control.

当我执行代码时,单击添加过滤器"将生成一个新文本框,但再次单击将创建一个新文本框,并处理掉它之前的文本框.相反,我想保留前一个文本框以及其中提交的任何数据.

When I execute the code, clicking "Add Filter" will generate a new textbox, but once clicked again will create a new one, and dispose of the one before it. Instead, I want to persist the previous textbox as well as any data submitted within it.

感谢您的帮助.

在aspx中:

<asp:Panel ID="pnlFilter" runat="server">

</asp:Panel>

在 aspx.cs 中:

In the aspx.cs:

protected void Page_Init(object sender, EventArgs e)
{
        LinkButton lb = new LinkButton();
        lb.ID = "lbAddFilter";
        pnlFilter.Controls.Add(lb);
        lb.Text = "Add Filter";
        lb.Click += new EventHandler(lbAddFilter_Click);
}


void lbAddFilter_Click(object sender, EventArgs e)
{
    TextBox tb = new TextBox();
    tb.ID = "tb" + DateTime.Now.ToBinary().ToString();
    pnlFilter.Controls.Add(tb);
}

推荐答案

对于任何试图做这样的事情的人:不要.相反,考虑信息流并了解有更好的方法来做到这一点.输入控件不需要动态创建.它们可以是静态的,并且在填写并提交时,该信息必须到某处(例如数据库、缓存、会话).到达那里后,在回发时,遍历您选择的存储中的所有项目并为它们创建一个显示.

For anyone else trying to do something like this: don't. Instead, think of the flow of information and understand that there is a better way to do it. The input control(s) do not need to be dynamically created. They can be static, and upon filling out and submitting on one, that information has to go somewhere (database, cache, session, for example). Once its there, on postback, loop through all items in your storage of choice and create a display for them.

这就是我所做的,它让生活变得更加轻松.希望它可以帮助某人.

That is what I've done and it has made life a lot easier. Hope it helps someone.

这篇关于ASP.NET 动态创建控件和回发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆