简体   繁体   中英

how to programmatically add more than one item in a webForm asp.net

I try to programmatically add item (like label, table, ...) in my webForm. I tried to create an event click on a button, to add labels each clicks. But every time, it stops to one label, and then nothing happens for the next clicks.

Here's my code for those who want to see what I tried :

protected void btn_Valid_Click(object sender, EventArgs e)
    {
               this.Page.Form.Controls.Add(new Label() { Text = "test" });
    }

Can we do this in asp.net or should I use another language (like javascript) ?

It only creates one Label because that one Label is lost during PostBack. In your click-event, you have to increase a counter for labels (and/or other controls), and recreate those in Page_Init . EACH and EVERY time the Page posts back. Memorize that counter in the ViewState. And as usual, I recommend this article about the ASP.NET Page Life Cycle

For those who want a real anwser to this follow this step, it works for me :

  1. Make creation (and not instanciation) in the Page_Init or Page_Load, because for each events those methods are called,
  2. For the example above, don't do kind of this.Page.Forms.Controls.Add(lbl_test) , try to find another way like storing the data of those label (in a String Array for example). Here's the code example :

protected void btn_test_Click(object sender, EventArgs e) { tabLabel[count_tabLabel] = "hello world"; // Do the if(IsCallBack) {} for avoid having your first label skipped count_tabLabel++; }

  1. In the Page_Load() function (basically written in the .cs) or by creating the function bellow, do a loop to add those labels to your webForm like this :

protected void Page_Init(object sender, EventArgs e) { for (int i = 0; i < cpt_l; i++) { Page.Form.Controls.Add(tabLabel[count_tabLabel]); } }

In fact the page is automatically reloaded, that is the asp page cycle life. So you need at each modifications on your webForm to reload all your items like labels, or more complexes things.

Hope it helps !

PS:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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