How to add controls dynamically when click button in asp.net?

前端 未结 3 1308
没有蜡笔的小新
没有蜡笔的小新 2020-12-18 03:36

I\'m trying to add controls dynamically

Code:

AddVisaControl.ascx

<%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"AddVi         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-18 04:01

    I will show one examples you can try it your own way

    An idea would be to create a list of buttons in which you'd store the buttons you created inbtnCreateDynamic_click

    you could have a method like:

    private Button CreateButton(string id, string name)
            {
                Button b = new Button();
                b.Text = name;
                b.ID = id;
                b.Click += new EventHandler(Button_Click);
                b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
                return b;
            }
    

    in btnCreateDynamic_click you could have something like:

    Button b = CreateButton("dinamicBtn"+myDinamicButtonsList.Count.ToString(),"dinamicBtn"+myDinamicButtonsList.Count.ToString());
    myDinamicButtonsList.add(b);
    and in the pageLoad for example you could do something like
    
    foreach(button btn in myDinamicButtonsList){
        form1.Controls.Add(btn));
    }
    
    List

    myDinamicButtonsList should be stored somewhere from where it could be retrieved after each request.

    EDIT: In page load you could have something like this:

    if(Session["myDinamicButtons"] == null){
        List

    i didn't tested it but it should work.

    also put on some information following may more help..

    Your button click event at the client will cause a page postback that will start the ASP.Net Page Life-cycle. enter image description here

    Your button click event on the server is a PostBackEvent and you should be able to use the same method call CreateMyButton() that you used in the Load or Init events.

提交回复
热议问题