Wednesday 15 June 2011

c# - How do add an EventHandler for a dynamically generated Button -


It is similar to these questions, but they do not help me (why would you explain below):

  • I am creating a C # aspx page that page grabs a bunch of data and then creates a table One column in the table contains a button that is dynamically created because it creates data (since the action of the button depends on the data in the table).

    Default.aspx

      & lt; Body & gt; & Lt; Form id = "form1" runat = "server" & gt; & Lt; Div & gt; & Lt; Asp: table id = "tblData" runat = "server" & gt; & Lt; / Asp: table & gt; & Lt; / Div & gt; & Lt; / Form & gt; & Lt; / Body & gt;   

    Defafult.aspx.cs

      Protected Zero Page_load (Object Sender, EventAgds E) {BuildHotel (); } Protected Zero BuildOutable () {// Table Header Row Creating and Tables TableHeaderRow hr_header = New TableHeaderRow (); TableHeaderHC_Cell = New TableHeaderCell (); Hc_cell.Text = "This column has a button"; Hr_header.Cells.Add (hc_cell); TblData.Rows.Add (hr_header); // Create cell to include our buttons table row = new table (); Tableclass Cell_V_button = New TableCell (); // button button BTN 1 = create new button (); Btn1.Click + = new event heredollar (this.btn1_Click); // cell, from the cell to the row and row, click the cell button from the cell. Control. Add (BTN1); Row.Cells.Add (cell_with_button); TblData.Rows.Add (line); } Secure zero btn1_Click (Object Sender, EventArgs e) {// Wonderful stuff}   

    Where I am going I understand that my event handler is not being left because it is the Page_Olload method However, if I take the BTN1 build and event handler to Page_load, I can not access them in BuildOtables!

    I see that in all code examples, BTN1 has been added statically to ATPX page, or it is dynamically created in Page_load. What is the best way to do what I am trying to accomplish?

    First create your ID You can tie this event:

      Button BTN1 = new button (); Btn 1.ind = "btn mybutton"; Btn1.Click + = new event heredollar (this.btn1_Click);   

    Ensure that each button has a unique ID Additionally, I personally move the code to Page_Init instead of Page_Load Will do it

  • No comments:

    Post a Comment