I have an ASP.NET web form on which I'm displaying a list of database items via user controls, generating the user controls dynamically - working fine.
Also on the page, I have an asp:dropdownlist filled with items that can be added to this database list. Along with this dropdown I have a button 'ADD'. My intent is that the user chooses and item, clicks add, and then the list of user controls on the form will include this new item.
I have all this working.
My issue is that the user control has a button 'DELETE', which removes the selected item from the list. That works, EXCEPT when I add a new item. Because my 'add' button event is always fired after Page_Load, even if I regenerate the list of user controls, the internal user control click events won't fire because the controls weren't created as part of Page_Load.
I need to know what I'm doing wrong, or best practices here, any advice. I tried to be precise in the description of the problem, but if I've not succeeded, let me know and I can add more details.
SIMPLE RESTATE: I need to know how to add a dynamically created user control to a page via a page button click event, and still have the user control internal click(etc) events firing.
Thanks for any help.
EDIT: Based on the feedback from the gentlemen here, and doing some further research related to their suggestions, I ended up implementing a solution based on what's presented on this page:
http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx
Here's a snippet showing how I dealt with this. This snippet resides in my PreInit event handler. Not exactly an elegant weapon for a civilized age, but sometimes a blaster is all you've got to use.
'Look to see if button for adding a new client number has been
'clicked. If so, call the sub to add the item NOW, so that it
'is able to have it's internal click events fire.
For Each control_string As String In Request.Form
Dim ctl As Control = Page.FindControl(control_string)
If (ctl IsNot Nothing) AndAlso (ctl.ID = "cmdAddClientNumber") Then
Me.AddClientNumberToList()
Exit For
End If
Next
On the button handler, you initially add the UserControl to the Page. OnPreInit (which will next be fired when the user clicks Delete on the UserControl), you should re-add the UserControl - so that it exists, and can handle the Delete button event.
You will need to devise your own state tracking mechanism to determine that you need to add the UserControl during PreInit. I generally use ViewState, as evidenced by this seemingly similar post.
Similar question:
How to create and use custom control with UpdatePanel added to the page programmatically
Dynamic control should be re-added to the control tree OnPreInit, see documentation:
PreInit - Create or re-create dynamic controls.
ASP.NET Page Life Cycle Overview
Related
I have the following scenario:
UserControlA contains a <asp:Button id="bSomeid" onClick="AddItem" /> with some code to an item to a shopping basket in AddItem.
UserControlB contains some LinkButton's that dynamically add a selection of UserControlA to the page in the OnClick event.
This is all done in an UpdatePanel. It is a little more complicated but I have pruned the information to what I believe is causing the problem, I will add more information if necessary.
The problem I have is that it takes 2 clicks for the AddItem event to trigger after I have added the items to the page after clicking the LinkButton.
I understand why this is happening - it is to late in the page cycle to register events for the next post back in the onclick - but can anyone think of a way around this? Can I force an event to be triggered on the next postback? I have tried to think of a way to run my code in page_load but I requuire access to the sender in the onClick.
Using .NET 4.0.
EDIT
I managed to find a way to get the link button sending the request in the Page_Load (using Request.Form["__EVENTTARGET"];) so I moved my code to the Page_load event. It still requires 2 clicks so I am assuming it isn't something to do with the onClick being registered to late.
Are there any other general things to check that could cause a button to require 2 clicks to post an event properly?
If your suspicion about being late in page life cycle is true then you can try using ScriptManager.RegisterAsyncPostBackControl method to register dynamically added controls in the link button click - considering that your button is within user control, you need to add public method into UserControlA that would actually register the button bSomeid1 and link button click from UserControlB would actually call the A control's method.
EDIT :
Another cause for button click not happening can be that button being dynamic control is not added in the page hierarchy when post-back happens (or it gets added very late in the page life cycle when the post back data is already processed). A really full-proof solution should add dynamic controls back to the page hierarchy in page_load it-self (and strictly maintaining same controls ids within hierarchy). If that's not possible then you can sniff the request (Request.Form) to detect the post-back.
In your case, you should ascertain if the button is indeed causing the post-back on each click. If yes, what is the POST data (Request.Form) for the first request - what is the __EVENTTARGET value on the first click (and post-back)? That should start your trouble-shooting.
On the other hand, a simple work-around could be to use html anchor element (you can still use link button) and have a javascript handler in the click event that would set some hidden variable and then submit the form (you can simulate the click on hidden button to trigger ASP.NET client side submit pipeline) . Now the hidden variable value can be used on the post-back to determine which link button has been clicked.
"Are there any other general things to check that could cause a button to require 2 clicks to post an event properly?"
Does it require two clicks on the control, or does it take accept a single click elsewhere on the screen, and then fire first time with a single click on the control?
I have my own (similar) issue with the Updatepanel where the first (expected) trigger does not fire and it seems that a single click elsewhere, and then the subsequent triggers fires first time (which totals 2 clicks)
[edit] Since you are working on this ATM, it may help me as well. Do you have a textbox with a trigger event on it? I do, and if I leave this blank (so that it does not fire) then there is no need for a second click.
On clciking a button in the page , I am adding an user control in to a place holder of the page.
The user control has a gridview which has a link button as template field and has a click event associated with it.
When I click the link button inside the gridview , the link button click event is not fired and also the user control disappears in the page.
Please suggest a solution
--You need to recreate all your dynamic controls at the early enough in the page lifecycle (page_load/page_init), so the asp.net will detect events and attach them.
try this knowledge post
http://support.microsoft.com/kb/317794
Why don't events of dynamically added user control fire on postback?
You need to recreate your dynamic controls on every postback - remember a new class instance of your page is created every postback, so any dynamic controls you created the previous time will need to be recreated.
see this article
and this one
I have a simple user control containing two text boxes which I am adding to placeholder on Button Click event. I am storing the number(count) of clicks in View state and running a loop using count to create all previously added user control. I am also adding IDs to each User control (appending "UC" and count). I have also checked in view source the ids are same each time they are created. I have another button which basically does an post back. I have EnableViewState enabled ="true" in all controlls all the way up to Page Level.
My problem is that User Input does not persist on postback. please advice. Should this not be happening automatically for me?
Have a look at this:
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
I've encountered minor problems with it on a web farm, but for simple deployments its use is pretty straightforward. (Comes with source code, and the web farm glitch is a pretty simple fix.)
You need to create your dynamic controls in the Page_PreInit event rather than Page_Load or in a Click event handler. That way, they'll be there before ViewState, and then your posted values are applied.
I thinks what is happening is that you are creating your controls during the click event handler which happens AFTER ViewState and PostBack have been applied. This means your controls will be created empty each time.
I'm trying to create a web page that will display an appropriate user control based on the selected value of a drop down list.
Basically the page layout is this:
Drop Down Selection
< User Control created based on drop down selection >
I have it half working... the controls are changing when the selection changes.
In OnInit(), I dynamically create the last selected control (whose value gets saved in session state because ViewState isn't available at OnInit).
When the drop down selection change occurs, I remove the old user control, and add a new one. The problem is: with the new control being added from the selection changed event, I'm not able to save changes from the user on the first postback. After the first post back, the selected control is created from OnInit instead of the Change event, and state is saved from then on, until the next selection change.
Here is the SelectionChanged method:
protected void SelectionChanged(object sender, EventArgs e)
{
SelectedValue = int.Parse(DropDownList.SelectedValue); //Store in Session
Control userControl = GetSpecificUserControl(SelectedValue);
PlaceHolder1.Controls.Clear(); // Remove old user control
PlaceHolder1.Controls.Add(userControl);
}
Any changes made to the new control by the user after SelectionChanged happens are not saved on the following post back. However, subsequent postbacks do get saved. At that point, the control is getting created in OnInit().
Is there some way to force the correct post back and ViewState when the control changes? Is it possible to force a page reinitialization after the control is changed?
What you need to do is keep the last known value of the DropDownList in the Session. Then:
OnInit:
Create whatever control is indicated by the saved value in the session
SelectionChanged Event
Remove whatever you created during OnInit
Create and add new control based on new DropDownList selection
Save new DropDownList selection in session
This way, on the next postback after a change you are re-creating the control that ViewState expected to find, and so it's state will be restored.
Dynamic controls can be very finicky. Often it is easier to create all of the controls you might possible need and set their Visible properties to false. This way they don't render to the browser at all. Then set Visible to true for just the controls you need when you need them.
This is the classic tear-your-hair-out problem with ASP.Net webforms. You have several options:
1) This is a bit of a hack, since it goes outside the intended page lifecycle a bit, but in my experience it's the most direct way of dealing with the problem. When the page posts back from the drop down selection event, simply poll Request["MyDropDownID"] for the selected value of the drop down control during Init() - don't wait for the OnMyDropDownChanged() event to set up your page.
2) Implement your own ViewState handling for your user controls. This requires digging into the ViewState documentation and overriding a number of methods.
3) Joel's solution. He beat me to it but I was trying to get first post :p
Other options involve posting values using javascript and such, but those get really messy.
If the list of options is not too big, you could just render all the user controls statically and use JavaScript/jQuery to show/hide the appropriate controls based on the value of the dropdown (onchange js event). You can use the dropdown value to extract the appropriate values from the user controls when saving.
You avoid the pain of dealing with dynamic controls, provide a more responsive UI when selecting from the dropdown (no postback), etc...
Don't add the control in the SelectedIndexChanged handler, add it during Page_Load. You'll just have to test the value of the dropdown each time the page loads, and load the correct control for that value.
I have a site that I am currently working on in ASP.NET 2.0 using the usual WebForm stuff and ASP.NET AJAX 1.0. Is it possible to bind an event to a dynamically created control after the Page.Load event?
I have a table <td> element that I am dynamically creating similarly to this code:
' Create Link Button
lnk.ID = String.Format("lnkDetails_{0}", dr("Id"))
lnk.Text = dr("Name").ToString()
lnk.CommandArgument = dr("Id").ToString()
AddHandler lnk.Click, AddressOf DetailsLink_Click
cName.Controls.Add(lnk)
This this code is looped over for each row in a database (and of course more cells are added to the table, including an ImageButton with an event. The events work flawlessly when I execute this code during events leading up to and including Page.Load. I need to be able to fill this table with current data, which is updated during a btnClick Event elsewhere on the page, which occurs after this Page_Load event, so I am populating with old data. If I change this code to Page.LoadComplete, events stop working.
This data is a summary display of various components of an application, things like somebody's name, which when updated on a 'detail' form, updates the database by partial postback (a requirement), then it needs to show the update in this 'summary' section after an update. Currently it takes 2 postbacks to actually see the change in the 'summary' section, so effectively the summary is 1 step behind the changes (clear as mud?)
What would be the best way for me to populate this table with current data (which is available during/after Page.LoadComplete), but still have an event fire when a link is clicked (the event causes an UpdatePanel to display the 'detail' form).
I also have jQuery at my disposal and the usual ASP.NET AJAX methods, also javascript is a requirement for the website, so I do not need to degrade for unsupported browsers.
This is my first ASP.NET web application and need some help figuring out the best way to make this happen (I'm well versed in PHP, Django and the usual ways to do web forms - things like having multiple forms on one page o_O).
Update:
There really isn't a good way to bind control events to controls after Page_Load. The overall architecture of the pages is there is one ASP.NET form encompassing the entire page, there is only 1 aspx page. I am using master pages (however it doesn't have any obvious implications to my issue).
The page is split into a left and right 'pane', the left is a summary of all the data (in an update panel), the right 'pane' has 6 'tabs' implemented each as their own user control, each with several form fields and an update button all in it's own UpdatePanel.
An update on any of these tabs only refreshes the summary panel (UpdatePanel.update()) and its own panel. The 'refreshing' and event binding of dynamic controls of the summary from the db happens during Page_Load and the Update Button event updates db data. (The control event happens after Page_Load). I want to avoid doing a double post to get the summary to update, any thoughts are helpful.
You need to postback the whole page after your data changes in the 'btnClick Event elsewhere on the page'. It sounds like you have an UpdatePanel and it sounds like this is catching the postback of your btnClick event handler. Put the btnClick outside the UpdatePanel or change its triggers so that your btnClick forces a postback/refresh of your data. Or, redesign your table so it's AJAXly-refreshed when you click on btnClick, it's hard to get you more details without knowing more about the structure of your page and controls.
Good luck!
You can bind to an event whenever you want. It's just a simple event after all. But not all places might be suitable because you have to take into account when the event fires. And in most cases this happens between Page_Load and Page_PreRender. That includes the click event on a LinkButton. In general, I would recommend to add your dynamically created controls in the Page_Init stage.
You have to add the controls before Page.Load in order to maintain ViewState between postbacks, so use the OnInit event handler for that.
But once they're added, you should be able to bind event handlers (such as OnClick) at any point during or after the Page.Load... for example in your grid's ItemDataBound (or something like) or in the Page.PreRender.