Event handling outside Page_Load or Page_Init - c#

Well if i'm creating an event programmatically and run it outside the page_load or page_init then it's not working. Do you have to write the code inside the page_load or page_init?
the code below is just a little example that works inside the page load or init but not outside.
protected void btnAddProduct_Click(object sender, EventArgs e)
{
Button b = new Button();
b.Text = "Add product";
b.ID = "btn_Back";
b.Click += new EventHandler(Button_Click);
form1.Controls.Add(b);
}

You can't add events outside the Init and Load events.
The Page object instance isn't persistent across calls, it is built every time you call that url, so every event handler added in another place than the Page_Load will be lost after the page content is sent.

Related

Add Event to Control added dynamic

I'm using asp.net and c# for webForm. I'm generating a dropDownList dynamically, but I can't execute an event for this control. Below some code:
DropDownList nuevoCmb = new DropDownList();
nuevoCmb.ID = "ddl" + num;
nuevoCmb.Items.Add("---Seleccione el Plazo---");
nuevoCmb.Items.Add("Corto Plazo");
nuevoCmb.SelectedIndex = 0;
nuevoCmb.AutoPostBack = true;
nuevoCmb.SelectedIndexChanged += new EventHandler(nuevoCmb_OnSelectedIndexChanged);
MainPanel.Controls.Add(nuevoCmb);
protected void nuevoCmb_OnSelectedIndexChanged(object sender, EventArgs e)
{
string temp = "";
}
You need to add the code that creates the control to every page request, including postbacks. If the control causes a postback and the code that recreates the control is not called, your event handler will not fire. .NET will eventually call your event handler once a control with the same ID is added during the page load.
You should add dynamically added controls in or before the page Init event. It also works if you add during page Load event. After the Load event, your custom control events bubble up and fire. So if you're adding controls dynamically, they have to be added on each post back, being loaded before the page Load event ends, at the latest.
I found an answer in the follow page: Creating Dynamic DropDownList Controls in ASP.Net
This example is fully functional, but only an asp html page, is not working using master page. Any suggestion!

Dynamic button click event created OnPreRender doesn't fire

I am creating a button dynamically in the PreRender event like this:
Button myButton = new Button();
myButton.Text = "Test";
myButton.Click += new EventHandler(myButton_Click);
myDiv.Controls.Add(myButton);
This button is render in the browser, but when I click the button, the click event doesn't fire. I tried to create an identical button in the PageLoad event and it works perfectly, but I must create this button it the PreRender event, since creating this dynamic button or not depends on a value which I get only in this event. What can I do so when I click a dynamic button created in the PreRender, the click event fires?
You should add your button to the page in the page's OnInit event and wire up it's click event during or before OnLoad and then you can enable/disable your button or make visible/invisible your button using the variable that you will have during the PreRender event. See Joel Coehoorn's answer to this question for more details. Otherwise try using a PlaceHolder control though that may end up being trickier.
protected override void OnInit (EventArgs e)
{
Button myButton = new Button();
myButton.Text = "Test";
myButton.Click += new EventHandler(myButton_Click);
myDiv.Controls.Add(myButton);
base.OnInit(e);
}
protected override void OnPreRender(EventArgs e)
{
myButton.Visible = myConditional;
base.OnPreRender(e);
}
Maybe create the button in the PreRender and bind the click event in PageLoad?
In PreRender you can create some var, which will tell you, that you need create button.
And on Render create that button by hand with need JavaScript or with sending form. But you can't use such simple syntax as +=EventHandler, more code need.
According to this link from MSDN, you must add button and event related to it if needed durign the OnInit() as explained here : MSDN Lifecycle
"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.
Use this event to read or initialize control properties."
To do so, try something like that :
protected override void OnInit(EventArgs e)
{
// Do some stuff here
base.OnInit(e);
}
You should move control creation earlier in the page lifecycle. Control events are fired after Load and before PreRender so OnLoad or anything earlier should do.
You should add the button on the preinit phase, otherwhise it won't fire
Asp net lifecycle
Use this event for the following (PREINIT):
Create or re-create dynamic controls.

Add EventHandler to Content Page

I have wired up the Button control on my Master Page in the Content Page as follows:
SiteMaster MasterPage;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MasterPage = (SiteMaster)Page.Master;
MasterPage.Button1.Click += new EventHandler(Button1_Click);
}
}
void Button1_Click(object sender, EventArgs e)
{
MasterPage.Button1_Click(sender, e);
}
However, whenever I click Button1 on the page (running under localhost), the Page_Load event fires!
What have I done wrong?
If it helps, the MasterPage.Button1_Click event runs a log in script, so there should be no recursive calls.
Is the issue here that the handler Button1_Click is not firing for you?
If so, the reason for this is because you are only assigning the event handler for the Click event on initial page load and not when the page is posting back.
Try assigning the event handler on initial load and subsequent postbacks like so:
protected void Page_Load(object sender, EventArgs e)
{
MasterPage = (SiteMaster)Page.Master;
MasterPage.Button1.Click += new EventHandler(Button1_Click);
}
Hope this helps.
Perhaps you want to wire your event up in the Page_Init as opposed to the Page_Load.
as far as your button click causing Page_Load to fire. Page_Load is always going to get fired because it's part of the page lifecycle.
see: http://support.microsoft.com/kb/305141 for page lifecycle details.
Page_Init: During this event, you can initialize values or connect any event handlers that you may have.
see also question: In asp.net, page_load occuring before radio button OnCheckedChanged event

Problems with IsPostBack

I have an .aspx page which sends a letter to a customer if a button on that page is clicked. Onclick the page calls itself, so the mail send class is in the same file. However I do not want the mail sent when the page is simply loaded. I want it send the letter when the button is clicked, so, I'm trying with the following code:
void page_Load(Object sender, System.EventArgs e)
{
if (IsPostBack)
{
SendMail();
}
}
But it doesn't work. What am I doing wrong?
Why not use the Button's Click Event then?
What you are talking about is you want to send an email only when a specific button is clicked. Then why not register to it's click event instead of bloating your page_load with extra code?
Button's click event is raised only when that button's click causes a postback. So, that's your best option.
Make an event handler for the button's click event (Just double click the button in Visual Studio's Designer).
Using Page_Load will result in emails being sent out when the user posts back in any circumstance, not just your button click.
Looks like the page does not find the correct event handler for the Page_Load, check the case and correct it to Page_Load
See if this works (replace your page_Load method with the following code):
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
if (IsPostBack)
{
SendMail();
}
}
You are currently relying on AutoEventWireup functionality to hook up your page events. This is slow and problematic and may be the cause of your issue. The method I gave you overrides Page.OnLoad and should correct the problem as well.
The Page_Load event is raised every time the page is posted, well by means of postback or callback, if you want to use server side events you should call you SendMail method in the button's click event:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && !IsCallback)
{
/*occurs the first time the page is loaded*/
}
if (IsPostBack)
{
/*occurs every time a postback is raised (e.g. by form submission) */
}
if (IsCallback)
{
/*occurs every time a callback is raised, e.g. by generating callbacks by means of AJAX/
}
}
protected void SendMail_Click(object sender, EventArgs e) { SendMail(); }
Read more at MSDN: ASP.NET Page Life Cycle.

asp.net user control event propagation trouble

I have a simple user control that contains some buttons that fire events which I want to be handled by the page using the control. I have my code setup as such:
public event EventHandler Cancel;
public event EventHandler Confirm;
public void Confirm_Click(object sender, EventArgs e)
{
if (Confirm != null)
Confirm(this, e);
}
public void Cancel_Click(object sender, EventArgs e)
{
if (Cancel != null)
Cancel(this, e);
}
but when I try to call these from the page that is using the control's page load event I don't get any of the custom events
ASPX Code
<%# Register TagPrefix="btg" TagName="CustomControl" Src="~/Search/CustomControl.ascx" %>
<btg:CustomControl ID="btgControl" runat="server" ></btg:CustomControl>
could this be because my buttons in the user control are within an update panel?
You shouldn't be seeing methods. You should be seeing events.
In your parent page's load, you need to do this:
myUserControl.Cancel += new EventHandler(myUserControl_Cancel);
You can hit tab,tab to auto-generate the method stub. That will look like:
void myUserControl_Cancel(object sender, EventArgs e) {}
Then, this code will fire after it is called in the method of your user control. In order for that code to fire, you'll have to assign the events to button events on your user control.
edit: myUserControl is the id of your user control. Also, some would argue that event handlers should be in your page's init method.
edit:
Is your user control properly referenced in the page? i.e. Are you registering the user control in web.config or using the reference directive in the page?
Also, did you try cleaning the solution and rebuilding? If your user control is dynamically created/loaded, you'll have to wire up the events in the same scope as the instantiated control. In order to dynamically load the user control, you'll have to have a placeholder in your page and do the following:
UserControl control = Page.LoadControl("~/ControlPath/ControlName.ascx");
((MyUserControlClass)control).Cancel += += new EventHandler(myUserControl_Cancel); // etc...

Categories