UserControl events not working for first time - asp.net

I am calling my user control in a web page dynamically.
For the first time when I click the button on user control, the event is not firing. When I click the same for a second time, the events are firing..
Can anyone help me?

Sounds like the hookup to the button OnClick event is not occurring on every page load, which is required.
Can you guarantee that the hookup is being performed when you add the control and after a poastback to the page? I always put my event hooks in the Page_Init or Page_Load event handlers and outside of any Postback check. Try putting a breakpoint on the Handler hook up and see if the breakpoint gets "hit" twice.
An event hookup for a button would look similar to:
protected void Page_Load(object sender, EventArgs e)
{
btnSearch.Click += new EventHandler(btnSearch_Click); // breakpoint on this line
}

The client id of the control is derived from the ID of all containing controls that are marked with the INamingContainer interface. So, make sure that ALL controls in the hierarchy have a fixed ID.
For example if you have a Button control inside a Repeater, the ID of the button and the repeater are concatenated to make the client ID for the button. So both the repeater and the button should have the same ID across postbacks.
You can compare the HTML for the first request with the HTML of the second request to quickly determine if this is the problem.

Assign an ID for your dynamically created control -- otherwise no events will be fired.

Are you waiting for the download of full page before pressing the button?
The events are javascript functions hidden by ASP.Net in the page, that maybe not present at the time of your clicking.

Related

updating Textbox.text in serverside code asp.net

I have a textbox in my default.aspx page that I want to update it's text property in an event handler but the change does not take place after executing the code .
void _gsc_Task_Completed(object sender, TaskEventArgs e)
{
TextBox1.Text = "New Value";
}
How ever , if I do this on the click event of a simple button the textbox.Text value
changes.
what is the difference between a custom event handler like _gsc_Task_Completed and a simple button click event ?
Text box is a server side control. when you change the text this work(change text) is client side so the event not firing. but when i click on a button the page is going to server and back so the event is firing.
You need to consider the page lifecycle: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
Either your event handler is being called to early (and clobbered by whatever is brought back from the client) or it is being called after the control was already rendered.
If I were you I'd put a breakpoint there as well as normal handlers for page onInit, onLoad, etc. See what order that handler is called (if at all) and what is below it on the callstack.

In asp.net, page_load occuring before radio button OnCheckedChanged event

I have two radio button on my asp.net page, with AutoPostBack = True
When I click on either of those, they each set a flag SaveData=False
However, when I click on them, the page_load event occurs first, so the page_load event saves the data, then the radiobutton_OnCheckedChanged event is triggered.
How can I trigger the OnCheckedChanged before the page_load event?
You can't.
You need to read up on the page lifecycle.
You can't trigger the OnCheckedChanged before radiobutton_OnCheckedChanged because that's the normal page life cycle.
You can check in Page_Load if Page.IsPostBack is true or not, and then don't save (or save) the data.
Troy - you will have to take care of this on the client side (javascript / jquery).
Your AutoPostBack = True causes the form to do a postback which calls page load.
Its all about how the page lifecycle and server side events work.
You can't the page always needs to load before events can be fired. This has to do with control creation, view state management, control state, etc.
What you want to do in your Page_Load is something like:
if(!this.IsPostBack)
{
// Do the stuff you want on the initial page load
}
Anything that you do not want to happen when the radio buttons are clicked, put it inside the if {} block. IsPostBack indicates that the page is processing a post-back event, which is what happens when you click one of your radio buttons.
You can't change the order/sequence of event handler execution. However you may move the code inside the page_load to another event handler.

Button click event handler before page load

I will describe my problem in simple way so it's not exactly what I'm trying to do but the idea is the same.Here is the problem:
I create dynamic buttons from code behind.I get some id from query string,create button with that id ,dynamic add event handler to click event,and add button to placeholder.I store the list of id-s in session and in page load method recreate these buttons and add to placeholder.One of the id-s is CurrentId and it's also stored in session.Buttons click handler do something like this
Button b=(Button)sender;
Session["CurrentId"]=Convert.ToInt32(b.ID);
In page load when I create buttons I want to set button text property different from others if id==Convert.ToInt32(Session["CurrentId"]) when list of id-s are gotten from session.But problem is that click event handler is called after page load,and when I create buttons in page load ,CurrentId in session hasn't been channged by click event handler.Can you suggest any solution to this situation?
It looks like you are attempting to update the buttons you have dynamically created after the click event has fired. Why not just change the button text within the click event as you have described?
i.e.
protected void button_Clicked(object sender, EventArgs e)
{
((Button)sender).Text = "Custom text for active button";
}
Also, you can always update the buttons on the PreRender event which occurs after the control click events but before the controls are served back down to the client.

Conditionally trigger a full page postback from a link button inside an update panel

How do I conditionally trigger a full page postback from a link button inside of an update panel?
I have a custom control that contains its own updatepanel with a link button nested inside of it. When the link button is pressed I want its event handler to have the option of either letting the control update as normal or doing a full postback on the page.
Here is the control hierarchy:
Page
Custom Control
UpdatePanel
LinkButton
Event handler Pseudo code:
LinkButton Click Handler Begin
If is a partial post back AND a full postback is needed
Page.DoFullPostback
End If
End Handler
Note: I aways need the partial postback to happen. I was considering injecting a __DoPostback in the controls markup but this seems hacky to me.
Thanks for your help!
Sorry, I'm not familiar with the VB, so my example source will be written in C#:
protected void btnLink_Click(object sender, EventArgs e)
{
bool isAsync = ScriptManager.GetCurrent(Page).IsInAsyncPostBack;
bool postBackIsNeeded = true;
if (isAsync && postBackIsNeeded)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnClick);
string postback = Page.ClientScript.GetPostBackEventReference(
btnClick,
string.Empty
);
ScriptManager.RegisterStartupScript(
btnClick,
btnClick.GetType(),
"postback",
postback,
true
);
}
}
The main idea is to change the type of postback of your LinkButton control. If neccessary it should be changed to full postback instead of partial during the async postback event. Right after this, another postback script should be generated and it should be executed as soon as the page will be returned to client.
And the last thing - use loop detection condition (if (isAsync && postBackIsNeeded) in my case) otherwise postback will be infinite.
The easiest approach is to create a hidden button somewhere on your page, outside of any UpdatePanels. When you need to do a full postback, use JavaScript to either click the button or issue __doPostback() to it. You can achieve a partial postpack programmatically in JavaScript by calling __doPostback() on an UpdatePanel itself, or to a button inside one.

Catching events from dynamically added ASP.NET User Controls

I have an ASP.NET web form which I am adding a variable number User Controls to. I have two problems:
The User Controls are added to a PlaceHolder on the form in the first PageLoad event (I only add them when "(!this.IsPostback)", but then when the form is posted back, the controls are gone. Is this normal? Since other controls on the form keep their state, I would expect these dynamically added ones to stay on the form as well. Do I have to add them for every postback?
I also have a button and an event handler for the button click event, but this event handler is never called when I click on the button. Is there something special I have to do to catch events on dynamically added controls?
Yes, you need to add them in every postback.
Yes... the control needs to be in the control hierarchy before asp.net dispatches the event (i.e. create the dynamic controls as early in the page lifecycle as possible).
1) You should add the controls on the Pre-init (Page life cycle)
2) You have to attach the event handler to the event of the created button.(events might occur much later in the page life cycle than the same events for controls created declaratively)
To achieve this, add your controls at page init instead of page load. (re-add at postback)
You'll need to know the id of the buttons added to bind them to the event.
I ran into a similar problem. I had a page that displayed a collection of custom web controls. My solution was to add an additional invisible web control so that when I clicked a button to add another control that I would just use the invisible one. Then on post back my load function would add another invisible control to the collection.
I figured out yesterday that you can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(savedState)
If IsPostBack Then
CreateMyControls()
End If
End Sub
I ran into the exact same problem and struggled through like 5-6 hours.
I'm posting this maybe someone like me could get help.
1) You should initialize your controls at Page.PreInit event. (In my case I had to add my controls to a place holder so I extended PreInit to load those controls before but you don't need to do that. It depends on your scenario.)
2) You should bind those exact methods to your controls after you initialize them in your Page.PreInit event.
Here is my sample code:
protected override void OnPreInit(EventArgs e)
{
// Loading controls...
this.PrepareChildControlsDuringPreInit();
// Getting ddl container from session and creating them...
if (GetDDLSession().Count != 0)
{
foreach (DropDownList ddl in GetDDLSession())
{
ddl.SelectedIndexChanged += SelectedIndexChanged;
phDropDowns.Controls.Add(ddl);
}
}
base.OnPreInit(e);
}
public static void PrepareChildControlsDuringPreInit(this Page page)
{
// Walk up the master page chain and tickle the getter on each one
MasterPage master = page.Master;
while (master != null) master = master.Master;
}

Resources