Add Event Click to a Button Asp.Net

0

I create a Button from code c #, now I need to add a method when I click on the ... I did this but it does not work

public void AgregarBoton()
        {
            Button miBoton = new Button();
            miBoton.ID = "BtnCheck";
            miBoton.ForeColor = System.Drawing.Color.Silver;
            miBoton.Font.Size = 9;
            miBoton.BackColor = System.Drawing.Color.Indigo;
            miBoton.Text = "CHECKOUT";
            miBoton.Click += new System.EventHandler(MiBoton_Click);
            miBoton.Width = 120;
            miBoton.Height = 30;
            PlaceHolder1.Controls.Add(miBoton);
        }
        public void MiBoton_Click(Object sender, System.EventArgs e)
        {
            Button bt = (Button)sender;
            Session["p"] = "fsdfsdfsf";
            Label2.Text = Session["p"].ToString();
        }
    
asked by Efrain Mejias C 07.08.2016 в 15:33
source

2 answers

2

I think you should analyze this article

How to: Dynamically create controls in ASP.NET using .NET Visual C #

You will see that when creating dynamic controls you must place this in the Init or Load events and in each post you must assign the event, otherwise you will lose the assignment and consequently the event will not be launched.

The truth is that if you can avoid creating controls like this, use Repeater

How to: Add a Repeater control to a Web Forms page

if you need to create a dynamic template that is generated according to the data you assign

    
answered by 07.08.2016 / 16:12
source
0
 public partial class Carro : System.Web.UI.Page
    {
         private Button miBoton = new Button();

    protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                    miBoton.Click += new System.EventHandler(MiBoton_Click); 
            }

        }
public void AgregarBoton()
        {

            miBoton.ID = "BtnCheck";
            miBoton.ForeColor = System.Drawing.Color.Silver;
            miBoton.Font.Size = 9;
            miBoton.BackColor = System.Drawing.Color.Indigo;
            miBoton.Text = "CHECKOUT";
            miBoton.Click += new System.EventHandler(MiBoton_Click);
            miBoton.Width = 120;
            miBoton.Height = 30;
            PlaceHolder1.Controls.Add(miBoton);
        }
        public void MiBoton_Click(Object sender, System.EventArgs e)
        {
            Button bt = (Button)sender;
            Session["p"] = "fsdfsdfsf";
            Label2.Text = Session["p"].ToString();
        }
}
    
answered by 07.08.2016 в 17:58