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

前端 未结 5 1406
予麋鹿
予麋鹿 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 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

提交回复
热议问题