views:

764

answers:

4

I have a user control that has several buttons.

On page_load, I want to run a method except if a specific button was pressed.

When I check the sender on page load inside the user control, I just get the name of the user control and not the button itself.

Is there a way that I can determine what button was pressed on page_load? Otherwise I will have to come up with some hacky method to solve the issue.

Thanks.

A: 

Can you create a property in your user control to return the clicked button (or set a flag or whatever), an set it in each button's click event inside the user control?

gfrizzle
+2  A: 

I think you can check Request.Form ("__EVENTTARGET") - that should contain the ClientID of your control.

This refers to the value of a hidden field the ASP.NET event handling framework uses to keep track of what the user clicked. When the user triggers a post-back, some JavaScript on the page sets this hidden field to the ClientID of the control you clicked before submitting the form.

Chris Roberts
Nope, that just sends back the name of the user control just like the sender property.
Ryan Smith
Where in the code for your user control are you adding the child controls?
Chris Roberts
It's actually a user control that's added to a SharePoint page through a custom web part.Ugly I know, but that's the specs of the project.
Ryan Smith
A: 

Are you sure you're handling the page model correctly? The Page Load event happens (to build the server side object model), then your control is going to handle the button click event bound to the control.

Page Load can come for any number of postback reasons besides buttons in your user control being clicked.

What about buttons in other controls on the page?

There's sometimes good reasons to do this, but I also I worry that you're just hacking around the ASP.NET page model.

Cade Roux
I understand that the button click happens after the page_load event, and that's what's causing me problems. This has always caused me problems too. I wish the button click events would happen before the page_load so I don't have to hack around this.
Ryan Smith
The page doesn't exist until it is created. Then it can handle the events. You really need to avoid putting any code in your page load which isn't about populating the object model.
Cade Roux
A: 

Here's a simple way to check if a specific button was pressed:

protected bool isButtonClicked(string buttonName)
    {
        bool isClicked = false;
        foreach (string ctl in this.Request.Form)
        {
            if (ctl.EndsWith(buttonName))
            {
                isButtonClicked = true;
                break;
            }
        }
        return isClicked;
    }
Geri Langlois