How to use Load and Unload events in a user web control? - asp.net

I swear to god I tried googling it.
I have a webcontrol that logs into the database the time and date of a page load, and same of page unload.
I can't set it up to save my life.
can somebody provide a solution?
Thanks!

You can use UserControl's Load and Unload events.
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
// Log to Database
}
protected void Page_Unload(object sender, EventArgs e)
{
// Log to Database
}
}
Here is ASP.Net Page Life Cycle

The page fires the load event, which recursively goes through all of its controls, including your user control, to fire that load event on it. same action occurs for Unload. The page controls it all, which is controlled by the module that controls the ASP.NET framework.

Related

Initialize variables before having anyone enter the web app

How can I initialize variables before my Web Application starts? I want to have, for example an Application type, to count number of logged in users in my website (it's an example, I have more variables that need initialization). How can I perform that?
It could be very useful if there was some event that would be called at the start of the Web App. I thought that I could check in each Page_Load event if a certain Session called, e.g Session["Started"] is null, and if it, redirect to an .aspx page for initialization. Or, even better, have a class called, e.g MyPage which inherits from System.Web.UI.Page and have her constructor get a function as an argument, which will be called after the initialization of the base class Page_Load.
Maybe I'm just bothering, is there any built-in event called that I can overwrite to initialize everything I want in the beginning?
You can use the Global.asax file for this. In particular you can use the Application_Start, Session_Start, Session_End events.
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
}
Here for more informations.

Aspx and Ascx lifecycles : avoid multiple select on database

I use an ascx user control for manage CRUD o database entity. I reuse this userc control in my aspx page for show in readonly mode the database data of a record on database. The user control have inside a simple FormView and an objectdatasource.
Now, in a aspx page that contains that ascx i have to know, in DATABIND time of the aspx some data of the record of the database that is considerate by the user control. User control are databind after the aspx page, and for this reason i don't have the data. I have to do a select in aspx page on database and after the user control do the same select.
How can i do for optimize this process?
ASCX base events may be fired after your ASPX's base events, but in the whole lifecycle, you can fire your own events.
You could define an Event on your ASCX, make your page register to this event, and then propagate your custom event from your ASCX to your ASPX, with whatever data you need in the arguments
rough example (may not compile) : in the ASCX
public partial YourControl : System.Web.UI.UserControl {
public event EventHandler MyControlDataBound;
public void FireMyControlDataBound()
{
if (MyControlDataBound!= null)
{
MyControlDataBound(this, new EventArgs());
}
}
protected void MyDataBound(object sender, EventArgs e) {
// ......
FireMyControlDataBound();
}
}
and in the ASPX
public partial class MyPage: Page
{
protected void Page_Load(object sender, EventArgs e)
{
yourUserControlInstance.MyControlDataBound += HandleYourDataInYourPage;
}
protected void HandleYourDataInYourPage(object sender, EventArgs e) {
// .. do whatever needed in your page, with your data
// if you have defined a custom Args class that inherits EventArgs, your could collect data here...
}
}
Feel free to create a class that inherits EventArgs to pass data with your event if you need this
You can pass your arguments to your UserContol in init event of your Page
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var control = (UserControl)this.FindControl("UserControlId");
control.Property = ...;//Pass User Control properties
}

Access textbox value in a header in a master page to .aspx.vb page

I created a textbox and a submit button in header(User Control) included in a master page
and I want to use that textbox value after clicking submit in my .aspx.vb page.
How can i access that, as the vb page is loaded first and then master page is loading ?
TextBox Val = (TextBox)this.Master.FindControl("TextBoxID");
The best way to communicate from UserControl to Page/MasterPage is using events
The best way to communicate from MasterPage to Page is using events
On this way you don't hardlink UserControls with their Pages/MasterPages and the Page with it's Master.
Add an event to your UserControl that is raised when the user clicks the button, for example:
In UserControl of type MyControl:
public delegate void SubmittedHandler(MyControl ctrl);
public event SubmittedHandler Submitted;
protected void BtnCLick(object sender, EventArgs e) {
Submitted(this);
}
Then add an handler to this event in your MasterPage, handle it and raise the Master's event again:
In Master's codebehind:
public delegate void MyControlSubmittedHandler(MyControl ctrl);
public event MyControlSubmittedHandler ControlSubmitted;
protected void Page_Init(Object sender, EventArgs e) {
this.MyControl1.Submitted += MyControlSubmitted;
}
protected void MyControlSubmitted(MyControl sender) {
ControlSubmitted(sender);
}
Then add an handler to this event to your page:
In your Page:
protected void Page_Init(object sender, EventArgs e) {
((SiteMaster)Master).ControlSubmitted += MasterControlSubmitted;
}
protected void MasterControlSubmitted(MyControl sender){
// do whatever you need to do
}
If you only need to access the TextBox from the page and you don't need to handle the click-event, you could also use properties to achieve this:
add a public property f.e. MyControlText in your UserControl that get/set the TextBox.Text property
add a public property f.e. MyControlText in your Master that get/set your UserControl's MyControlText property
Now you can get/set this property from your page in this way:
((SiteMaster)Master).MyControlText = "Hello World";

Passing Value Between Web User Controls - DifferentQuestion

I want pass values between web user controls without writing any code to the main page which user controls are put on. I do something like that but after doing that I need to click double to pass the value.
The example of what I've done :
Department User Control (Code-Behind)
protected void Page_Load(object sender, EventArgs e)
{
int productId = ProductUserControl.selectedProductId;
... doing some bind work with productId
}
Product User Control
public static int selectedProductId;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lvDepartments_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "selectDepartment")
{
selectedProductId = int.Parse(e.CommandArgument);
}
}
Thanks in advance...
In your Department User Control you are trying to get the value of selectedProductId before it is set in the Product User Control. That's why you don't get the value you expect until you postback twice.
You'll need to get it after the Product User Control sets it in the ItemCommand event. Perhaps placing the Department User Control code in the Page_LoadCompleted... though I'm not sure if that will work either.
Another way to do it is to have Product User Control set a public property in Department User Control instead of having Department User Control try to read a property in Product User Control.
The issue seems to be a Page Lifecycle issue.
http://www.robincurry.org/blog/content/binary/o_aspNet_Page_LifeCycle.jpg
I'm sure there's a better way than that as well.
Try using delegates to achieve this more cleanly, example here

Asp.NET: UserControl's BubbleEvent not being handled by repeater or page

I have a user control inside of a repeater. The user control has an ImageButton, which when clicked, should raise an event to the page which will handle the event:
//Button onClick event in user control
protected void btnOpenOption_Click(object sender, ImageClickEventArgs e)
{
RaiseBubbleEvent(sender, e);
}
The following are two methods on the page. One to handle a BubbleEvent from a child control, the other to handle the repeater's ItemEvent command:
protected void rptProcessOptions_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//do something...
}
protected override bool OnBubbleEvent(object source, EventArgs args)
{
//do something else...
}
I've read that the repeater ItemCommand handler should listen for the BubbleEvent from the child control and subsequently handle it, but it's not. The OnBubbleEvent handler on the page is not picking it up either. In other words, the event is just getting lost. I know it's firing because I can see that when I step through in the debugger.
I've used RaiseBubbleEvent before successfully, but never inside a repeater, so I'm not sure if what I'm attempting is correct. Any thoughts?
ItemCommand is only fired if the EventArgs is an instance of RepeaterCommandEventArgs.

Resources