Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

ASP.NET: Find which control caused a postback

From Wiki

Jump to: navigation, search

Summary: Pass the page to the function and the control that caused the postback will be returned from the function

  1. Public Function GetPostBackControl(ByVal page As System.Web.UI.Page) As System.Web.UI.Control
  2.     ' Find which control caused the postback  
  3.     Dim control As Control = Nothing
  4.     Dim ctrlname As String = page.Request.Params("__EVENTTARGET")
  5.     If Not (ctrlname Is Nothing) AndAlso Not (ctrlname = String.Empty) Then
  6.         control = page.FindControl(ctrlname)
  7.     Else
  8.         Dim ctrlStr As String = String.Empty
  9.         Dim c As Control = Nothing
  10.         For Each ctl As String In page.Request.Form
  11.             If ctl.EndsWith(".x") OrElse ctl.EndsWith(".y") Then
  12.                 ctrlStr = ctl.Substring(0, ctl.Length - 2)
  13.                 c = page.FindControl(ctrlStr)
  14.             Else
  15.                 c = page.FindControl(ctl)
  16.             End If
  17.             If TypeOf c Is System.Web.UI.WebControls.Button OrElse TypeOf c Is System.Web.UI.WebControls.ImageButton Then
  18.                 control = c
  19.                 ' break  
  20.             End If
  21.         Next
  22.     End If
  23.     Return control
  24. End Function

This Hack is part of the ASP.NET Hacks collection

439 Rating: 3.7/5 (3 votes cast)