Friday 12 July 2013

How to Find the Control that caused Postback in ASP.NET

In this article, I am explaining how to find the control’s ID that caused the postback i.e. find the source of postback in ASP.Net.
In this article I have taken into account the following controls
1.     Button
2.     ImageButton
3.     LinkButton
4.     RadioButton
5.     CheckBox
6.     RadioButtonList
7.     CheckBoxList
8.     DropDownList
9.     TextBox
 
All controls accept Button and ImageButton use JavaScript for causing a postback. To enable postback on these controls one has to set AutoPostBack property to true.
When you set this property to true, __doPostBack function is called on event which causes a postback.
The __doPostBack function is not visible in Source of the page until you place a LinkButton or set AutoPostBack to true for any of the above discussed controls.
<script type = "text/javascript">
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    theForm.__EVENTTARGET.value = eventTarget;
    theForm.__EVENTARGUMENT.value = eventArgument;
    theForm.submit();
}
}
</script> 
 
The __doPostBack function simply stores the below two arguments in two hidden fields
1.     eventTarget – The name of the control that caused the postback
2.     eventArgument – The argument to be sent to server.
In two hidden fields which also appear only when AutoPostBack is set to true or LinkButton is placed on the page.
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
 
To get the control’s ID that caused the postback the code is as below
 
C#
if (IsPostBack)
{
    string CtrlID = string.Empty;
    if (Request.Form["__EVENTTARGET"] != null &&
        Request.Form["__EVENTTARGET"] != string.Empty)
    {
        CtrlID = Request.Form["__EVENTTARGET"];
    }
}
 
VB.Net
If IsPostBack Then
  Dim CtrlID As String = String.Empty
  If Request.Form("__EVENTTARGET") IsNot Nothing And
     Request.Form("__EVENTTARGET") <> String.Empty Then
      CtrlID = Request.Form("__EVENTTARGET")
  Else
End If
 
The above code only works for those controls that use __doPostBack function
For Button and ImageButton you will need to do using the following Trick
<asp:Button ID="Button1" runat="server" Text="Button"
  OnClientClick = "SetSource(this.id)" />
 
<asp:ImageButton ID="ImageButton1" runat="server"
OnClientClick = "SetSource(this.id)" />
 
On the OnClientClick property of the Button and ImageButton I am calling the SetSource JavaScript function
<script type = "text/javascript">
    function SetSource(SourceID)
    {
        var hidSourceID =
        document.getElementById("<%=hidSourceID.ClientID%>");
        hidSourceID.value = SourceID;
    }
</script>
 
The above function stores the ID of the control in hidden field when the Control is clicked
  
<asp:HiddenField ID="hidSourceID" runat="server" />
 
Now on Server side we can get the ID in the following way
C#
 
if (IsPostBack)
{
    string CtrlID = string.Empty;
    if (Request.Form[hidSourceID.UniqueID] != null &&
        Request.Form[hidSourceID.UniqueID] != string.Empty)
    {
        CtrlID = Request.Form[hidSourceID.UniqueID];
    }
}
 
VB.Net
If IsPostBack Then
   Dim CtrlID As String = String.Empty
   If Request.Form(hidSourceID.UniqueID) IsNot Nothing And
    Request.Form(hidSourceID.UniqueID) <> String.Empty Then
     CtrlID = Request.Form(hidSourceID.UniqueID)
   End If
End If
 
The complete function is given below. I am displaying the ID of the control that caused the postback using a JavaScript Alert.
      
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        string CtrlID = string.Empty;
        if (Request.Form["__EVENTTARGET"] != null &&
            Request.Form["__EVENTTARGET"] != string.Empty)
        {
            CtrlID = Request.Form["__EVENTTARGET"];
        }
        else
        {
            //Buttons and ImageButtons
            if (Request.Form[hidSourceID.UniqueID] != null &&
                Request.Form[hidSourceID.UniqueID] != string.Empty)
            {
                CtrlID = Request.Form[hidSourceID.UniqueID];
            }
        }
        ClientScript.RegisterStartupScript(this.GetType(),
            "sourceofpostback",
            "<script type='text/javascript'>" +
            "window.onload=new function(){" +
            "alert('Control ID " + CtrlID +
" caused postback.');}" +
            "</script>");
    }
}
 
            
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  If IsPostBack Then
     Dim CtrlID As String = String.Empty
     If Request.Form("__EVENTTARGET") IsNot Nothing And _
        Request.Form("__EVENTTARGET") <> String.Empty Then
        CtrlID = Request.Form("__EVENTTARGET")
     Else
        'Buttons and ImageButtons
        If Request.Form(hidSourceID.UniqueID) IsNot Nothing And _
           Request.Form(hidSourceID.UniqueID) <> String.Empty Then
            CtrlID = Request.Form(hidSourceID.UniqueID)
        End If
     End If
     ClientScript.RegisterStartupScript(Me.GetType(), _
     "sourceofpostback", _
     "<script type='text/javascript'>" _
     & "window.onload=new function(){" _
     & "alert('Control ID " & CtrlID _
     & " caused postback.');}" _
     & "</script>")
  End If
End Sub

No comments:

Post a Comment

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...