I am dynamically loading the web user control into the ajax tab container, and with the help of ActivetabChanged event i am binding the relevant user control into that particular tab.
In each user control i have the data lists contains thousands of records, which i am binding on user control page load event.
I am putting the binding code into !page.IsPostback, now here comes my problem, when ever i changed the tab change event, Page.IsPostback returning true, and datalist does not bind, i force to put the code into !page.IsPostback becaue i have to fire the datalistCommandEvent.
So is there any solution for this problem?
You need to track whether tab has changed or not. Typically, you can store the previous active tab in the view-state and compare with the current active tab in page_load. If the tab has changed then bind the data-list from user-control in the active tab (by invoking public method in your user control that will do the binding of data-list).
Related
I have a button and a panel. When the user clicks the button it loads a usercontrol and adds it to panel.Controls. I need to bind a grid in the usercontrol when the usercontrol first loads (Page_Load) but not when the user clicks a button inside the usercontrol, aka triggers a postback in the usercontrol. I can't use Page.IsPostback because it returns true when the user clicks the main button which loads the usercontrol. What can I do?
It's primitive, but you can check for any control that caused the postback by comparing the value coming from:
Request.Form.Get("__EVENTTARGET")
This returns the uniqueID of the targeted control; check this to determine which button caused the postback, and act accordingly.
You can give the buttons inside of the user control a CommandName and check the value of the CommandName. You can also check the type on object sender to determine the control that caused the post back.
Don't forget that you will have to re-add the user control on each post back after it is dynamically created (in an event that occurs before Page Load), so you will need to implement a mechanism to determine that the user control was added in the panel.
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
From local forum i understood that PreInit can be used to handle the following
PreInit()
>Master pages can be called dynamically
>Themes can be set dynamically
>Programatically add controls to controls collection
and i read Init() is for
Init()
In this event, we can read the controls properties (set at design time). We cannot read control values changed by the user because that changed value will get loaded after LoadPostData() event fires.
Question
I am not getting the point "We cannot read control values changed by the user".Where do
users change the value of control?.Example would help me to understand the point.
PreInit: Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
Init: Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
Lets say you have a textbox, a dropdownlist, some check boxes... the user enters data into them and you want to read their values by writing
var text = myTextBox.Text;
var selectedItem = ddl.SelectedItem;
this you cannot do before after the LoadPostData method has been called.
This page gives a pretty good summary of the different events and what they should be used for http://msdn.microsoft.com/en-us/library/ms178472.aspx. It says that PreInit should be used for ie. creating dynamic controls and Init for setting properties on them.
On the first post, you show several controls, say a textbox and a submit button.
The user types code into the textbox and click submit.
The user has changed the value of the control when he typed it in the textbox and it then got posted back to the page.
You will not be able to access the value typed in until LoadPostData has processed.
This is the pretty much the same with all other server side controls.
PreInit:
Initialize master page , user controls , dynamic controls
Init :
set the properties of controls
The value is changed through PostBack. The changes in the form data is determined by the current ViewState (which isn't loaded until later) vs the form data. Seeing as that isn't loaded until later, then you can't read any control values at that point.
I dynamically load one of many user controls based on which tab the user clicks. I store the selected tab index in view state. The user control has a checkbox on it that fires an OnChanged event. My problem is that if I load the user control in Page_Load, the checkbox event doesn't fire because the control didn't get created in time. If I load the user control in Page_Init, the page doesn't know which user control to load I believe because the ViewState isn't loaded yet. How can I store which user control to load AND get the events on the user control to fire?
The best strategy I've found has been to create all the controls in the Page_Init event, and set their Visible property to false (in Page_Load in your case) if they aren't supposed to be present on the rendered page.
Edit
Another option is to determine which controls to load based on some other criterion (besides ViewState). For example, if you make the current tab one of your query string parameters, that data will be available on the request during Page_Init.
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.