Thursday, December 9, 2010

Raising an Event from Web User Control


 To demonstrate how to raise an event from a web user control we create a web-user control as follows.
First create a new website into this add a Web User Control by right clicking on project then selecting add new item from popup menu I Kept name of web user control  WebUserControlI chose the checkbox that asked if want to save code in separate file ,by coding language is c#.

My Code In side WebUserControl.ascx is as follows

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class WebUserControl : System.Web.UI.UserControl
{
    public delegate void OnLoginClick(object sender,LogMeEventArgs e);

    public event OnLoginClick LoginClickHandler;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void BtnLogin_Click(object sender, EventArgs e)
    {
        string Email=TxtEmail.Text;
        string Password=TxtPassword.Text;

        if (LoginClickHandler != null)
        {
            LogMeEventArgs LogMeEventArgsObj = new LogMeEventArgs(Email, Password);
            this.LoginClickHandler(this, LogMeEventArgsObj);
        }
    }
    protected void BtnReset_Click(object sender, EventArgs e)
    {
  TxtEmail.Text = string.Empty;
        TxtPassword.Text = string.Empty;
    }

    public void DisplayMessage(string Message)
    {
        LblConfirmationMsg.Text = Message;
    }
}

public class LogMeEventArgs
{
    public LogMeEventArgs(string pEmail,string pPassword)
    {
        this.Email = pEmail;
        this.Password = pPassword;
    }
    public string Email
    {
        get;
        set;
    }
    public string Password
    {
        get;
        set;
    }
}
Here point to note that I created LogMeEventArgs class with two public property Email & Password.The Constructor of this class can set this properties.
    Now Inside out ‘WebUserControl’ class I defined a delegate that wil be used to create an event as follows
    public delegate void OnLoginClick(object sender,LogMeEventArgs e);

Further I created an event in this class using this delegate as follows
    public event OnLoginClick LoginClickHandler;

My WebUserControl.ascx contain code as follows
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Panel ID="ControlContainer" runat="server" Width="185px">
<table border="1">
    <tr>
        <td colspan="2" style="text-align:left;">
            <asp:Label ID="LblConfirmationMsg" runat="server" Text="Please Enter Login Creadential ! " ForeColor="Red" Font-Bold="true"></asp:Label>
        </td>
    </tr>
    <tr>
        <td style="font-weight:bold;">Email:</td>
        <td>
            <asp:TextBox ID="TxtEmail" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td style="font-weight:bold;">Password:</td>
        <td>
            <asp:TextBox ID="TxtPassword" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>
            <asp:Button ID="BtnLogin" runat="server" Text="Login"
                onclick="BtnLogin_Click" />
            <asp:Button ID="BtnReset" runat="server" Text="Reset"
                onclick="BtnReset_Click" />
        </td>
    </tr>   
</table>
</asp:Panel>

Here simply I am adding to textboxes one from email & other for password,there are two button one for reset & other for submit.
Fig 1.1(Web-user control)
Reset button’s click event contain code to empty the two textboxes discussed above.
I am using submit button’s click event to raise an event, Here I first created an object of LogMeEventArgs which is instantiated with appropriate value from textboxes.Then I am conditionally raising an event ‘LoginClick’ as follow
            this.LoginClickHandler(this, LogMeEventArgsObj);
the condition I am putting is that it must be handled in parent aspx page.
This event is suppose to be handled by parent aspx page,if not handled then condition ‘LoginClickHandler’ will be null so no event will be raised.If the event is handled in parent aspx page then
It is call corresponding method from aspx page.
Following code is part of page_load of aspx here we are wiring the web user control event with a event handler in aspx namely ‘WebUserControl1_LoginClickHandler’.this event handler is nothing but a method whose signature resemble signture of delegate in webuser control that correspond with event
‘LoginClickHandler’
WebUserControl1.LoginClickHandler += new WebUserControl.OnLoginClick(WebUserControl1_LoginClickHandler);   
Full Code of Default.aspx.cs here I dragged the new web user control on default.aspx page is as follows
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebUserControl1.LoginClickHandler += new WebUserControl.OnLoginClick(WebUserControl1_LoginClickHandler);   
    }
    protected void WebUserControl1_LoginClickHandler(object sender, LogMeEventArgs e)
    {
        if ((e.Email == "sangram2681@gmail.com") && (e.Password == "sangram"))
        {
            Response.Write("Welcome " + e.Email);
            WebUserControl1.DisplayMessage("Thanks For Logging");
        }
        else
        {
            WebUserControl1.DisplayMessage("Never Mind,Please Try Again!");
        }
    }
}
Code In side my Default.aspx is as follows
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
           
        <uc1:WebUserControl ID="WebUserControl1" runat="server" />
           
    </div>
    </form>
</body>
</html>

When we will run default.aspx enter right emailid & password it display welcome message on aspx page.



(Fig 1.2 showing welcome message)

Then passes a message to be displayed on control through webusercontrols DisplayMessage() function.
   If Login credential is wrong we get try again message on web user control but no welcome message on aspx page

(Fig 1.3 showing Login Failure Response)

  Putting break point in right places on aspx.cs & ascx.cs will help to check how event transfer from webusercontrol to aspx page.

No comments:

Post a Comment