简体   繁体   中英

ASP.NET C# Issue Adding event handler to ImageButton CodeBehind

I'm having problems adding an event to an ImageButton. I have to create a set of buttons depending on a selected option from a DropDownList. The buttons are created successfully with Database data, but I'm can't attach the OnClick functionality.

The created buttons must share the same Handler.

protected void cmbServ_SelectedIndexChanged(object sender, EventArgs e) {
  ServiceID = cmbServ.SelectedValue.ToString();
  ServiceName = cmbServ.SelectedItem.ToString();

  DataTable dtFirstTab = new DataTable();
  dtFirstTab = mySQLConn.getTable(qryCarry); // LOAD DATA FROM DB

  foreach (DataRow row in dtFirstTab.Rows) {
     FTabBtn = "btn"+(Convert.ToInt32(row["SKU_Credito"])).ToString();
     FTabIconURL = row["SKU_Icon"].ToString();

     Panel dvFirstTab = new Panel();
     dvFirstTab.CssClass = "col-xs-2";

     ImageButton IB = new ImageButton();
     IB.ID = FTabBtn;
     IB.ImageUrl = FTabIconURL;
     IB.Click += new ImageClickEventHandler(btnX_click); // <-- PROBLEM

     dvFirstTab.Controls.Add(IB);
     pnlIcons.Controls.Add(dvFirstTab); // pnlIcons exists in HTML
}

protected void btnX_click(object sender, ImageClickEventArgs e) {
   string Obj = ((ImageButton)sender).ClientID;
   Cantidad = Convert.ToInt32(Obj.Substring(3, (Obj.Length) - 3));
   txtMonto.Text = "$" + Cantidad.ToString();
}

All the buttons appear correctly, but when I click on them they just fire a "submit" action, acting like there's no OnClick assigned.

No CodeBehid example:

If I add this line in HTML (I removed asp tags)

ImageButton ID="btn10" runat="server" ImageUrl="MontoLogo_10ST.png" OnClick="btnX_click"

It does work as intended.

Any ideas? Thanks a lot!

Creating controls dynamically in ASP.NET webforms usually seems easy at the beginning, but problems are very common when it comes to handling events. Even if you assign your event handler correctly, the event handler is not run in a postback until you re-create all the dynamic controls early in page lifecycle. This explains why the sample with the ImageButton on the ASPX works whereas the dynamically created buttons don't.

See this page for details on creating controls dynamically. The most important part is the warning that basically says: if you need to add dynamic controls, better don't.

Usually you can find a way to create all the necessary controls in markup, for instance using a Repeater control. The big advantage of the repeater is that you have control about the markup that is created.

The following sample outlines the necessary steps:

  1. Place a repeater on your aspx-page. If pnlIcons serves no other purpose than being the container for the dynamically created buttons, substitute it by the repeater. Use the Header- and FooterTemplate properties to add the markup that surrounds the ImageButtons (eg the div for dvFirstTab).
  2. Think about which data you need to assign to the image button. In your case, the fields "SKU_Credito" and "SKU_Icon" seem to be required.
  3. Place the Image button in the ItemTemplate of the repeater and bind the properties "Id" and "ImageUrl" to the corresponding fields.
  4. Add a Command event handler and bind the CommandArgument property to a value that helps you discern between the image buttons.
  5. In the command event handler, you can use the CommandArgument to discover which button has been clicked. Add the appropriate code that handles the command.
  6. In the SelectedIndexChanged event handler, read the data from the database and bind the repeater to the result. This creates the rows in the repeater with the ImageButtons.

Ok, I've found the reason. The event handling must be assigned in Page_Load event, so I moved everything inside a method and called it from Page_Load, calling it from "SelectedIndexChanged" doesn't work . It's working now.

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM