简体   繁体   English

在运行时问题 ASP.Net 中添加控件

[英]Adding controls in runtime problem ASP.Net

I put a link on a page and onclick i wrote some code to add some controls after clicking,我在页面上放了一个链接,onclick 我写了一些代码来添加一些控制点击后,

    DropDownList newDropdownlist = new DropDownList();
    panel.Controls.Add(newDropdownlist);
    CheckBox newChkbox = new CheckBox();
    panel.Controls.Add(newChkbox);
    TextBox txt = new TextBox();
    txt.ID = "txtPhoneValue";
    panel.Controls.Add(txt);

My Problem is when i click on this link it add these controls one time, but if i clicked again it don't add more, seams its removing the previous added controls and re add them again.我的问题是,当我单击此链接时,它会添加一次这些控件,但如果我再次单击它不会添加更多,接缝它会删除以前添加的控件并重新添加它们。

I want to add more and more each link click.我想添加越来越多的每个链接点击。

Ok, these added controls are not persisted anywhere between postbacks.好的,这些添加的控件不会在回发之间的任何地方保留。 So, you should add them every time the page reloads.因此,您应该在每次页面重新加载时添加它们。

Consider using some flags (stored in the Session for example) to indicate that additional controls must be added.考虑使用一些标志(例如存储在 Session 中)来指示必须添加其他控件。

Your controls're disappearing, as they're not stored anywhere (the page forgets about them on postback).您的控件正在消失,因为它们没有存储在任何地方(页面在回发时忘记了它们)。 Remember that, on each postback, your page has to be recreated.请记住,在每次回发时,您的页面都必须重新创建。

There're quite a few good articles about working with dynamically created controls.有很多关于使用动态创建的控件的好文章。 Also to fully understand what the problem is, it's neccessary to familiarize yourself with the page lifecycle.此外,要充分了解问题所在,您还需要熟悉页面生命周期。

Here're two articles that really helped me:这里有两篇对我很有帮助的文章:

You need to re-create the controls ( with the same IDs! ) on post-back, you can do this in the CreateChildControls method.您需要在回发时重新创建控件(具有相同的 ID! ),您可以在CreateChildControls方法中执行此操作。

It's worth looking at the Page Life-Cycle of ASP.NET to understand when and where stuff can be modified.值得查看ASP.NET 的 Page Life-Cycle以了解何时何地可以修改内容。 If it's to late, it won't get added to the ViewState etc, so it's worth understanding especially when using dynamically created controls.如果为时已晚,它不会被添加到 ViewState 等中,因此值得理解,尤其是在使用动态创建的控件时。

How is this link construct??这个链接是如何构造的?

If your link control is an html control (client control) the behaviour you're experienced is right.如果您的链接控件是 html 控件(客户端控件),那么您所经历的行为是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM