how to create an asp button dynamically and add event to it

前端 未结 5 1355
予麋鹿
予麋鹿 2021-01-21 07:06

I\'m trying to create a button dynamically on asp.net,but I can\'t add the event to it.What is wrong or missing below?

Thanks in advance

$

         


        
相关标签:
5条回答
  • 2021-01-21 07:41

    If I were right, you create buttons in Page_Load.

    If it is check for postbacks.

    if(!postback)
    {
       create your buttons.
    }
    
    0 讨论(0)
  • 2021-01-21 08:01

    This should do the trick:

    protected void Page_Load(object sender, EventArgs e)
    {
        Button b = new Button() { ID = "btnEdit", Text = "Edit Member" };
        b.Click += (sd, ev) => {
            // Do whatever you want to be done on click here.
            Button me = (Button)sd; // This creates a self-reference to this button, so you can get info like button ID, caption... and use, like this:
            me.Text = "Yay! You clicked me!";
        };
        form1.Controls.Add(b);
    }
    
    0 讨论(0)
  • 2021-01-21 08:02

    I think your trying to mix server side and client side events here.

    The html attribute OnClick is a client side, when a user clicks on the button it fires a piece of JavaScript The server event OnClick happens when a user clicks a button and it posts back to the server, which allows you to hook functions (server side) into that event.

    Are you looking for server side or client side?

    To add a client side event you can do

    btn2.Attributes.Add("onclick","my_javascript_function");
    

    To add a server side event you can do

    btn2.Click += new System.EventHandler(this.MyMethod); 
    

    Where this.MyMethod is a method already seutp to handle the server side button click.

    0 讨论(0)
  • 2021-01-21 08:02

    Create a method for adding all Your dynamical controls as below

    public void AddControls()
    {
        Button btn2 = new Button();
        btn2.ID = "btnEdit";
        btn2.Text = "Edit Member";
        btn2.Click += new EventHandler(btnEdit_Click);
        form1.Controls.Add(btn2);
    }
    

    and then call that method in Page_Load() Event & out side of the IsPostBack block as below

    protected void Page_Load(object sender, EventArgs e)
    {
    
        if (!IsPostBack)
        {
    
        }
        AddControls();
    }
    

    because for dynamically added control's view state will not load before Page_Load() evnt. go through this link for more info http://msdn.microsoft.com/en-us/library/vstudio/hbdfdyh7(v=vs.100).aspx

    0 讨论(0)
  • 2021-01-21 08:06

    read the article about the asp.net webforms life-cycle http://msdn.microsoft.com/en-us/library/ms178472.aspx. you have to create/recreate your controls everytime when loading the page (e.g. OnLoad-Method)

    http://www.asp.net/web-forms/videos/aspnet-ajax/how-to-dynamically-add-controls-to-a-web-page

    0 讨论(0)
提交回复
热议问题