16 July 2013

Determining the Control that Caused a PostBack

Public Shared Function GetPostBackControl(ByVal page As Page) As Control

    Dim res As Control = Nothing
    Dim ctrlName As String = Page.Request.Params.Get("__EVENTTARGET")

    If ctrlName IsNot Nothing And ctrlName <> "" Then
        res = page.FindControl(ctrlName)

    Else

        Dim c As Control = Nothing

        For Each ctl As String In page.Request.Form
            c = page.FindControl(ctl)
            If TypeOf (c) Is WebControls.Button Then
                res = c
                Exit For
            End If
        Next

    End If

    Return res

End Function

Si usa così:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim coso As Control = GetPostBackControl(Me)

    If coso.ID = "xxx" Then
        ' fai qualcosa...
    End If

End Sub

Testato sui Button.
Trovato qui.