1

I want to capture which button is clicked in page load method of code behind file. Button is user control button and It does not post back. Since it used by many other forms, I don't want to changes that button. I tried this

Dim ButtonID As String = Request("btnRefresh.ID")

But it doesn't work. Is it possible to know without touching in user control and using Javascript? Thank you

taymyinl
  • 295
  • 4
  • 15

1 Answers1

0

As described here How to check whether ASP.NET button is clicked or not on page load:

The method: Request.Params.Get("__EVENTTARGET"); will work for CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work for Button controls such as Buttons and ImageButtons

But you have a workaround, first of all you have to define a hidden field in the Parent Page. In this field you will store which button inside the user control was clicked using javascript/jquery. And then in your Parent Page Page_Load method you just read the hiddenField.Value property:

JQuery

1) Add listener to every input type submit button:

    $(document).ready(function () {
        $("input[type=\"submit\"]").on("click", function () {
            alert(this.name);
            $("#hiddenField1").val(this.name);
        });
    });

2) [Better one] Add listener to some indentificable div inside the user control and delegate the event to child inputs like this:

    $(document).ready(function () {
        $("#someElementOfUserControl").on("click", "input[type=\"submit\"]", function () {
            alert(this.name);
            $("#hiddenField1").val(this.name);
        });
    });

Javascript

Since everything done with JQuery can be done with Javascript you can do the following (i will not write both samples, just one):

    function handleClick(event) {
        alert(event.target.name);
        document.getElementById("hiddenField1").value = event.target.name;
    }

    var inputsInUC = document.getElementsByTagName('input');
    for (i = 0; i < inputsInUC.length; i++) {
        inputsInUC[i].addEventListener('click', handleClick, false);
    }

Remember to define this javascript after all your html elements.

EDIT:

Also, for the completeness of the answer let me tell you that the proper way in case you can change the user control behaviour is to use events as described here How do i raise an event in a usercontrol and catch it in mainpage?

Community
  • 1
  • 1
DiegoS
  • 816
  • 1
  • 10
  • 26