Event handling for dynamically generated controls - c#

I am working on a module where I am basically generating all the controls on the page dynamically using XSLT. They are being rendered and added to the mark up right. Here the problem is that I want to write event handling for this dynamically generated controls and I am not sure how to achieve that because in perfect development environment, we normally double click on our control on aspx page and .NET creates a related event for you in the back on the aspx.cs page.
Any ideas?

Dynamically-added controls generally do not survive postback.
No amount of double-clicking, or even typing the expected names of the controls with _selectedIndexChanged is going to get you what you want.
This is ASSUMING (please let us know if I'm right or wrong) that you are adding HTML controls, not ASP.NET controls dynamically.

You'll need to create a method with the appropriate handler and wire it up to your dynamically created controls when you create them.
i.e.
protected void MyHandler(object sender, EventArgs e)
{
//Do some stuff
}
when you create your controls
LinkButton lb = new LinkButton();
lb.ID = "lbexample";
lb.Click += MyHandler;
Page.Form.Controls.Add(lb);
But it's very important that on your postback, you rebuild these controls as they were or the event won't fire. You'll need to recreate the controls first so that the event can be raised, so any data that you'll need to create the controls will have to be available on the post back using whatever state mechanism you're comfortable with.

If you want to execute client-side events, you can specify the name of the method to fire (or the code itself) by adding the appropriate attribute.
For example, if you want to fire myCheckBox_OnClick when the user clicks your dynamically generated checkbox, you can do the following:
myDynamicallyGeneratedControl.Attributes.Add("onclick", "myCheckBox_OnClick");
You could also generate the javascript code that is to be executed and add it to the page through the page's ClientScript.RegisterStartupScript method.

Related

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:
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 (e.g. the div for dvFirstTab).
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.
Place the Image button in the ItemTemplate of the repeater and bind the properties "Id" and "ImageUrl" to the corresponding fields.
Add a Command event handler and bind the CommandArgument property to a value that helps you discern between the image buttons.
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.
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!

prevent the page to post back on button click while event will work

I have written a code in VB.NET in which there are around 300 asp controls and all of them are creating dynamically with more than 6 condition per control (like If control = dropdownlist then some code Elseif control = radiobuttonlist then some other code).
Now I want to write events for some controls but due to postback, when event is fired all of the controls are getting flushed.
When I set button1.onclientclick="return false" for button, the page stopped post back but the event also stopped working.
I have an option to save the values of controls in view state then recreating the controls and then refill the values to dynamic controls. This option will increase my line of execution.
Is there any other method though which I can prevent the page to post back on asp control event so that my asp control persists with entered values in it and also my event will work.
this is the Code1
this is the Code2
Create your dynamic controls OnPreInit Event of Page, Hope this solves your problem
override protected void OnPreInit(EventArgs e)
{
CreateDynamicControls();//Function which creates all dynamic controls
}
I have used JavaScript and Ajax to achieve my requirement.
I have called JS function for button's onclick and Textbox's onchange (like: btn1.Attribute.Add("onClick",JSFunction(); return false;) [return false is to prevent postback].
Then I used ajax post method to do my stuff on .vb page.

Click event doesn't fire in UpdatePanel even with IsPostBack check

I'm developing simple WebForms application, where I'm trying to catch simple click event of Button ASP.NET Control from the UpdatePanel.
Button wasn't added in MarkUp part of project. It was added dynamically from the CodeBehind and also event was added dynamically too to the static class.
Here is code:
http://ideone.com/bnntkb (CodeBehind only, because MarkUp holds just only the ScriptManager and UpdatePanel controls ).
First of all, I think the issue related to the Page.IsPostback and I have tried to use:
if (Page.IsPostBack) PageSetup();
But nothing happens, it just not firing the .Click event either.
Why do I have such a problem and how to fix it?
Thanks!
Please see what happens when you put PageSetup() into the Page Init procedure. Dynamically created controls are supposed to be created there.
Maybe some UpdatePanel initialization takes place earlier in the Page Life Cycle.
Also, dynamically created controls must be created each time the Page is created, even in PostBacks.

adding an event handler to a dynamically created checkbox (aspx, c#)

So my problem is that I want to add an event handler to a dynamically created CheckBox. I have already looked at other ways to do this, and decided that creating a dynamic table which contains my CheckBoxes is the best option for me. I have not added these CheckBoxes to the Control Tree because I need to manage the ViewState manually. Either way, my code works in every way except that my CheckBox's CheckChanged Event does not fire. I am adding this eventhandler to my CheckBox in my pageLoad event, however, any page event I try seems to give me the same results:
CheckBox chbxLv1 = new CheckBox();
chbxLv1.ID = "DymanicallyCreatedIDForIdentification";
chbxLv1.AutoPostBack = true;
chbxLv1.CheckedChanged += new EventHandler(this.checkChanged);
/* Way lower in my code */
protected void checkChanged(object sender, EventArgs e)
{
//Some code goes here which never seems to execute... grrr
}
I thought that this may be a problem with the ViewState at first and did quite a bit of research on that. I'm now thinking I am doing something dumb with adding an event handler. I'm not sure why this event never fires, but I'm a little new at adding events to a control. Do I need a delegate here?
--Roman
In order for dynamically loaded controls to be handled properly during the ASP.NET Page Lifecycle, they need to be added to the page during OnInit (or prior to LoadViewState, really) otherwise their state information will not be maintained and you can, in fact, corrupt the viewstate depending on how/where things are added in the page's control graph.

What if you want webpart communication before Page_Load?

I am needing to create some dynamic controls at Page_Load in the consumer webpart. In the Provider webpart I did some hacking and got it so I could get a controls value before viewstate is loaded in Page_Init.
So basically what I want is for webparts to be able to communicate before Page_Load.
[ConnectionConsumer("FormRID Consumer","FormRIDConsumer")]
public void InitializeProvider(MyControl.IFormRID provider)
{
theProvider = provider;
FormRID = theProvider.FormRID;
}
That method doesn't get called until after Page_Load. This is a big problem for me because my consumers Page_Load depends on FormRID being set and accurate. I can't move my Page_Load code into Page_LoadComplete either because I am needing to create dynamic controls with viewstate(viewstate isn't restored after Page_Load)
So is there some work around I can use so that I can communicate before Page_Load.
Have you tried subscribing to the web part zone's Init event and placing your InitializeProvider() there? I believe it is fired before OnLoad or OnInit events of user controls and web forms.
You should use on OnPreRender event instead of on Load, beause onLoad occurs before WebPart connection executes.
Here is one example of what you could expect using OnLoad and OnPreRender events http://blog.mastykarz.nl/web-part-requires-clicking-twice-apply-ok-button-apply-changes/
I ended up having to create my own webpart communication.
It ended up much cleaner than ASP.Net's and communication can happen as early as OnInit inside of the webparts.

Categories

Resources