Responding to Command button clicks in Page_Load

P

Paul Hodgson

I have quite a few pages that have multiple command buttons on them - for
example one button might be to logout, and others might be to display
different segments of the data being shown. The important point is that
what gets displayed in the page depends on which command button was clicked
in the postback. I'd assumed that I could handle this by sorting out what
action to take in the Click event handlers for the buttons, but that doesn't
work because the event isn't raised until after Page_Load has completed and
the HTML output has presumably already been determined.

So if I can't use the Click event, how do I determine during my Page_Load
code which button has been clicked and therefore what output to display?

Thanks

Paul
 
M

MSFT

Hi Paul,

In the Form_Load, you can check the string:

Request.Form.ToString ()

The last item in the string should be the name of button you click.

Luke
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
P

Paul Hodgson

Interesting. A very convenient workaround. I tried that and it works for
Button controls but not for LinkButton controls (which is what I would have
preferred to have though I guess it's not essential). If you hit a
LinkButton then the identity of the LinkButton doesn't seem to get added to
the Form data. Which raises two additional questions:
1. Is there any similar workaround for LinkButtons.
2. Is this an 'approved' workaround or is it a hack that happens to work at
the moment but could easily get broken by a future .NET release?

So far the only alternative I've come up with is to manually add some
client-side Javascript to the buttons which sets the value of a hidden
control when each Button (or LinkButton) is clicked. Then back on the server
I can read the value of this hidden control to figure out what button was
clicked. AFAICS that should work, but it looks messy so I don't really want
to do that. (Plus it seems to be exactly the kind of manual boilerplate
coding for managing the controls that I thought ASP.NET was supposed to
release us from).

Paul
 
M

MSFT

Hi Paul,

I just found a better solution which also work for a linkbutton:

Page.Request.Form["__EVENTTARGET"]

Every Form in ASP.NET have a hidden filed "__EVENTTARGET", we can get the
event sender form this field.

Luke
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top