Handling Page lifecycle events - c#

I am a VB.NET Developer trying to learn C# in my spare time. Please see the code below:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;//event handler code
}
private void Form1_Load(object sender, EventArgs e)
{
string test = "got here";
}
}
This is a Windows Form app. If I add the event handler code to the constructor then Form1_Load handles the load event.
Now see the Web Forms app below:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string s = "got here";
}
}
Page_Load is fired without any event handler code?
My question is: Are Page Life Cycle events automatically wired to function names e.g. Page_Load automatically handles the page load in c# ASP.NET? Why does this not apply to Windows Forms? Where do you put the Event Handler code in windows forms? the .designer?

In Asp.Net you can set AutoEventWireup value. Please check this article https://support.microsoft.com/en-us/kb/324151
However when I need to handle an event the easiest way for me is going to the aspx source view, find the the runatserver control and specify my handler there. For example:
<asp:TextBox ID="txtCustomer" runat="server" />
As you type "on..." the list of events is shown (events are identified by ray icon), select OnLoad and Create.
<asp:TextBox ID="txtCustomer" OnLoad="txtCustomer_Load" runat="server" />
Now go to your cs code behind file and you'll see default handler was created there.
protected void txtCustomer_Load(object sender, EventArgs e)
{
}
Another option is going to Design View, right click on the control and go to properties. Click on the ray icon and add your handler.

Winform do not auto fire event as Asp.Net because winform has not page life Cycle.
To handle a event in winform, you select a component in design mode. Look at the right panel, you will see the events tab. There are alot event here. Double click to handle it.

Related

Creating a load event for text label in windows application c#

I am new to C# programming language. I am trying to create a windows form application in c# .net using VS 2012. I have created a text label and I want to display a text when the application is loaded. I see only click event rather than load event. would anyone please suggest what to do? (I am expecting something like "lblText_Load")
The label does not have an event for loaded. You can either use the Form's Load event, or the OnShown event.
I suggest using the OnShown event because this will be triggered after the form is loaded and displayed. The OnLoad event for the form occurs when it begins to load not after.
You can use the form's Load event. See MSDN for additional information.
private void Form1_Load(object sender, System.EventArgs e)
{
lblText.Text = "w00t \o/";
}
On the load event of the form you can do what you want.
private void Form1_Load(object sender, System.EventArgs e) {
lblText.Text = "Evaluation Tool";
}
Forms have lots of events you can use (Load, Activated, Shown , etc.)

How do I get my asp:Button to execute code in the OnClick event?

First off... I'm a noob to both ASP.net and C#. I'm updating a page that already exists to add a button..
My code..
<div style="padding: 10px;float: left;"><table><tr><td><asp:Button id="DoSomething" Text="Build Patch" runat="server" OnClick="DoSomething_click" /><br /></td></tr></table></div>
This lives in my ascx control... the code behind is...
protected void DoSomething_click(object sender, System.EventArgs e)
{
Response.Write("<script> alert('Hi');</script>");
}
It gets wired up on the default.aspx page in
<%# Register Src="~/ui/MyView.ascx" TagName="MyView" TagPrefix="UC" %>
and is used in a asp:repeater...
<UC:MyView PB=<%# Container.DataItem %> runat="server"></UC:MyView>
The repeater creates the buttons inside a <td>
I supose my question is how do I wire up the onclick for these buttons? I debug and my DoSomething_click method never hits.
Basically you need to pass your ButtonClick event from UserControl to your webpage ( that contains this userControl). This is known as Bubble up of events
User control portion:
Define your OnClick event for the Button. However, in this event you will pass this to your .aspx page.
public partial class MyView : System.Web.UI.UserControl
{
public event EventHandler SomethingButtonClick;
protected void DoSomething_Click(object sender, EventArgs e)
{
//pass the event up to the aspx page. also called bubbling up the event.
if (this.SomethingButtonClick != null)
this.SomethingButtonClick(this, e);
}
}
Your page containg the UserControl:
Set the event handler for SomethingButtonClick event in Page_Init() event as :
protected void Page_Init(object sender, EventArgs e)
{
MyView1.SomethingButtonClick += new EventHandler(MyView_SomethingButtonClick);
}
Add/Define this MyView_SomethingButtonClick in your page code behind itself.
protected void MyView_SomethingButtonClick(object sender, EventArgs e)
{
//handle the event
Response.Write("<script> alert('Hi');</script>");
}
First off, try specifying type="text/javascript" inside of your script tag:
<script type="text/javascript">alert('hi');</script>
Assuming that doesn't work:
If I understand correctly, you are trying to link the dynamically created button to the code in the codebehind. This can get very, very weird. I would recommend using a "proxy function" of sorts. Create a javascript function elsewhere on the page that gets called by the button(s)' click event. This javascript function can then initiate a postback from there. I'll see if I can find the example I've used elsewhere.
EDIT: I can't find my original example, but this is a good reference: ASP.NET postback with JavaScript
Please note that the __doPostBack() function has TWO underscores, not one.

Creating an event for a textbox and AJAX Update Panel Control

I wanted to create a "Click" event for a textbox in C# (as there isn't any).
So, this way
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "txt1OnClick")
{
txt1_Click();
}
txt1.Attributes.Add("onclick", this.Page.ClientScript.GetPostBackEventReference(txt1, "txt1OnClick"));
}
private void txt1_Click()
{
ImageMap1.ImageUrl = "guide/1.jpg";
}
Then I wanted to load the image without reloading the page.
So I used the AJAX UpdatePanel Control and this worked fine with
protected void Button1_Click(object sender, EventArgs e)
{
ImageMap1.ImageUrl = "guide/1.jpg";
}
But not with the event I created, because the compiler doesn't identify my new events as
a real event or something I couldn't figure out.
I added the button1_click event according to Step 8 of "Refreshing an UpdatePanel Control with an External Button".
The click event of textbox is not shown in this option:
So my question is is there any way to add this event within System.Web.UI.WebControls.TextBox class or, to make this event visible within the above option?
So that I can include click event of the textbox within the Triggers of the update panel.
If you try to create a Click event for a TextBox, every time a user clicks your textbox you'll trigger a postback to the server (even to evaluate if you need to do something as part of handling the event). This is very inefficient - you should handle clicks in the browser, using JavaScript and then trigger the UpdatePanel using client-side logic.
This lets you trigger a call to the server if you need it but avoid it when you don't. If you have a server-side event handler, your code will post back to the server (reloading the page) every time the user clicks the TextBox.
You can read this link (and others) about using __doPostBack() on the client side to trigger an UpdatePanel to perform a postback.
http://encosia.com/easily-refresh-an-updatepanel-using-javascript/

Delegates, UpdatePanels and ascx controls

I have built an ascx control that is part of many different components of my application. There is a Previous and Next button on this control, which should be signaled to the parent aspx page. This is done by having the parent page add some Delegates for postbacks, such as OnPreviousClicked, OnNextClicked etc.
Everything in this app is 'ajaxified' with an updatepanel. Now I notice that my app breaks if I don't set the delegates on every single Page_Load call in the parent. In other words, if I don't ALWAYS set the delegates in the Page_Load of the parent aspx, then the ascx ends up with null delegates and an exception. Am I coding stuff correctly?
// inside the control
public event EventHandler OnPreviousClicked;
private void PreviousButton_OnClick(object sender, EventArgs e)
{
if(OnPreviousClicked != null) {
OnPreviousClicked(this, e); // or whatever args you want
}
}
// and inside the Page code-behind
private void Page_Load(...)
{
MyUserControl.OnPreviousClicked += new EventHandler(myHandler);
}
// OR inside the Page aspx, you also could just set the OnPreviousClicked property.
<xx:MyUserControl ID="MyUserControl1" runat="server" OnPreviousClicked="myHandler" />
See http://asp.net-tutorials.com/user-controls/events/.
If all you're doing is signaling the clicking of a button, I would have your ASCX control raise a simple event instead. That way each page can listen for the event if they need to and the controls can function regardless if anybody is listening.
First declare the events in your ASCX codebehind:
public event System.EventHandler NextSelected;
Then you create your button click events that raise the event.
protected void btnNextSelected_Click(object sender, EventArgs e)
{
if (EmployeeSelected != null)
{
NextSelected(this, new EventArgs());
}
}
Then in your parent ASP.Net pages you can add your ASCX control (we'll call it NavControl) and create methods that listen for these events.
NavControl.NextSelected += new EventHandler(NextPageRedirect);
protected void NextPageRedirect(object sender, EventArgs e)
{
Response.Redirect("~/ViewEmployee.aspx", false);
}
Note that with this you don't have to create the event handler or method and you can still use the nav control on your page. It should also eliminate the issues you are having with the delegates.
remember each postback has to restart your code. The event handlers don't get serialized to viewstate so you have to set them up again.
That is the expected behavior in asp.net.
The entire page life cycle occurs even when it is a partial postback (update panel). So in order for the events to fire, you will have to wire them up programmatically during page_load or declaratively in your markup (if those delegates you mentioned are events).

There has to be a way to get my data bound at the correct time

Say aspx page called theParent has a DataGrid control named theDataGrid and a UserControl named theUserControl , and theUserControl has a button named theUcButton .
Yes, I know, very imaginative naming.
When theUcButton is clicked , a session variable is changed.
This session variable is a select parameter for the datasource of theDataGrid.
However, because of the order of stuff called in the page lifecycle, when theUcButton is clicked and a postback is generated ,
theParent controls are loaded before theUserControl resets the session variable, and theDataGrid does not show the new data until the next postback .
How to I get what I want to work?
I am using 3.5 if that matters.
Here is example code for your user control to raise an event.
public partial class WebUserControl : System.Web.UI.UserControl{
public event EventHandler Updated;
protected void Button1_Click(object sender, EventArgs e)
{
//do some work to this user control
//raise the Updated event
if (Updated != null)
Updated(sender, e);
}}
Then from your .aspx page, you'll deal with the new event just like usual
<uc1:WebUserControl ID="WebUserControl1" runat="server" OnUpdated="WebUserControl1_Updated" />
Code behind:
protected void WebUserControl1_Updated(object sender, EventArgs e)
{
//handle the user control event
}
You can declare an event as a member of the UserControl class, raise it, and handle it in the Page class.
You can also use other events like Page.PreRender() to pick up things after the user control's events.
The easiest way would be to hold off on the databind until the later in the lifecycle, such as the Page.PreRender event as joelt suggested. If you do the bind then, you should have the session variables.

Categories

Resources