473,549 Members | 2,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Please Help! How to identify which button was clicked?

Hi all and thanks in advance,
I am stuck! I can't figure out how to identify which button was clicked on my ASP.NET page in the PostBack event? So what I am trying to do is to is to have an if statement like as follows in the PageLoad:

private void Page_Load(objec t sender, System.EventArg s e) {

if (!Page.IsPostBa ck) {

//do something here

} else {

if (btnSave.clicke d)

//do something here

else

//do something else

}

I have my methods btnSave_Click and other buttons setup. It is just that when the buttons are clicked they still go through the Page load event and within the pageload event I need to differentiate which one of the buttons are clicked since it is essential to my code.

Am I crazy for wanting to do something like this? It was very easy to do before with ASP?

Thanks for your input!

Nov 18 '05 #1
7 16008
Amadelle wrote:
Hi all and thanks in advance,
I am stuck! I can't figure out how to identify which button was clicked
on my ASP.NET page in the PostBack event? So what I am trying to do is
to is to have an if statement like as follows in the PageLoad:
private void Page_Load(objec t sender, System.EventArg s e) {

if (!Page.IsPostBa ck) {

//do something here

} else {

if (btnSave.clicke d)

//do something here

else

//do something else

}

I have my methods btnSave_Click and other buttons setup. It is just
that when the buttons are clicked they still go through the Page load
event and within the pageload event I need to differentiate which one of
the buttons are clicked since it is essential to my code.

Am I crazy for wanting to do something like this? It was very easy to
do before with ASP?

Thanks for your input!


I know there's a way to do this, not off-hand, but I am going to ask
'why?'? Since you have the events coded already, you'll know which
button when you get there (to one of them). Plus 'cancelling' the event
may be tough if that is something in mind (in Page_Load, if you want to
cancel or stop right there and redisplay).....

I'm curious as to why you're wanting to do this, if you can share...

--
Craig Deelsnyder
Microsoft MVP - ASP/ASP.NET
Nov 18 '05 #2
Amadelle,

If all of the buttons are of the same type then you can cast sender as the button directly like this:

Dim MyButton As Button = CType(sender, Button)

Then you can tell which button was clicked like this:

Select Case MyButton.ID
Case "MyButton1"
'---Do Something
Case "MyButton2"
'---Do Something Else
End Select

If you have different types of buttons you'll need to find out which type you're dealing with first before you may cast:

Select Case sender.GetType. ToString
Case "System.Web.UI. WebControls.Ima geButton"
'---Cast to image button here
Case "System.Web.UI. WebControls.Lin kButton"
'---Cast to link button here
End Select
--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
"Amadelle" <am******@yahoo .com> wrote in message news:O$******** ******@TK2MSFTN GP12.phx.gbl...
Hi all and thanks in advance,
I am stuck! I can't figure out how to identify which button was clicked on my ASP.NET page in the PostBack event? So what I am trying to do is to is to have an if statement like as follows in the PageLoad:

private void Page_Load(objec t sender, System.EventArg s e) {

if (!Page.IsPostBa ck) {

//do something here

} else {

if (btnSave.clicke d)

//do something here

else

//do something else

}

I have my methods btnSave_Click and other buttons setup. It is just that when the buttons are clicked they still go through the Page load event and within the pageload event I need to differentiate which one of the buttons are clicked since it is essential to my code.

Am I crazy for wanting to do something like this? It was very easy to do before with ASP?

Thanks for your input!

Nov 18 '05 #3
"Amadelle" <am******@yahoo .com> wrote in message news:O$******** ******@TK2MSFTN GP12.phx.gbl...
Hi all and thanks in advance,
I am stuck! I can't figure out how to identify which button was clicked on my ASP.NET page in the PostBack event? So what I am trying to do is to is to have an if statement like as follows in the PageLoad:

The best solution I've found to this problem is to not do it.

Don't ask in Page_Load which control caused the PostBack. Instead, handle the postback event of each control:

private void btnSave_Click(o bject sender, EventArgs e)
{
// Action when Save clicked
}

private void btnCancel_Click (object sender, EventArgs e)
{
// Action when Cancel clicked
}
--
John Saunders
johnwsaundersii i at hotmail

Nov 18 '05 #4
I have come across this problem before. Sometimes you need to know before the event handler fires which button was clicked, particularly if you are creating dynamic controls or something that needs to be in page_load based on the button press.

The solution so far is to do a HttpContext.Cur rent.Request[] of the buttons id. If the request comes back null, the button was not pressed. If the Request comes back with the ID of the button (essentially just a marker anyway) then it was that button that was pressed.

Example:
Page_Load:

// adding the button
Button oButton = new Button();
oButton.ID = "PRESSME1";
oCell.Controls. Add(oButton);
....
Somewhere else in PageLoad

....///testing for the button being pressed.
if (HttpContext.Cu rrent.Request["PRESSME1"] != null)
// the button was pressed. do something like add a dropdown list orsomething.
Another tricky one is trying to tell if a DropDownList or Checkbox marked as AutoPost has caused a postback without using event handlers. In this case you can use the JavaScript that .NET creates and hijack the "__event_target " form variable.
Do a request on the __EventTarget and whatever ID comes back is what caused the postback --- if the postback was caused by a DropDown or CheckBox or something that has AutoPost back. If a submit button caused the post back the __eventtarget is empty but you can do a request of the button's ID as described above.

Andrew S.
"John Saunders" wrote:
"Amadelle" <am******@yahoo .com> wrote in message news:O$******** ******@TK2MSFTN GP12.phx.gbl...
Hi all and thanks in advance,
I am stuck! I can't figure out how to identify which button was clicked on my ASP.NET page in the PostBack event? So what I am trying to do is to is to have an if statement like as follows in the PageLoad:

The best solution I've found to this problem is to not do it.

Don't ask in Page_Load which control caused the PostBack. Instead, handle the postback event of each control:

private void btnSave_Click(o bject sender, EventArgs e)
{
// Action when Save clicked
}

private void btnCancel_Click (object sender, EventArgs e)
{
// Action when Cancel clicked
}
--
John Saunders
johnwsaundersii i at hotmail

Nov 18 '05 #5
"Andy Z Smith" <An********@dis cussions.micros oft.com> wrote in message
news:A8******** *************** ***********@mic rosoft.com...
I have come across this problem before. Sometimes you need to know before the event handler fires which button was clicked, particularly if you are
creating dynamic controls or something that needs to be in page_load based
on the button press.
The solution so far is to do a HttpContext.Cur rent.Request[] of the buttons id. If the request comes back null, the button was not pressed. If
the Request comes back with the ID of the button (essentially just a marker
anyway) then it was that button that was pressed.
Example:
Page_Load:

// adding the button
Button oButton = new Button();
oButton.ID = "PRESSME1";
oCell.Controls. Add(oButton);
...
Somewhere else in PageLoad

...///testing for the button being pressed.
if (HttpContext.Cu rrent.Request["PRESSME1"] != null)
// the button was pressed. do something like add a dropdown list orsomething.

Another tricky one is trying to tell if a DropDownList or Checkbox marked as AutoPost has caused a postback without using event handlers. In this
case you can use the JavaScript that .NET creates and hijack the
"__event_target " form variable. Do a request on the __EventTarget and whatever ID comes back is what caused the postback --- if the postback was caused by a DropDown or CheckBox
or something that has AutoPost back. If a submit button caused the post
back the __eventtarget is empty but you can do a request of the button's ID
as described above.

I've yet to find a situation where I've needed to know in Page_Load what
control posted back. It's always been possible to allow the postback events
and postback data events to fire and then to process the results of those
events in later handlers, like in the PreRender event. I have found this to
be true even for cases where the entire control hierarchy is created
dynamically.

Also, the techniques you mention are very dependant on the specific
implementation of the current version of ASP.NET. The two underscores in
"__EVENTTAR GET" are an indicator that this is an internal,
implementation-dependant name, subject to change whenever they feel like it,
or just whenever they want to play with your mind...
--
John Saunders
johnwsaundersii i at hotmail
"John Saunders" wrote:
"Amadelle" <am******@yahoo .com> wrote in message news:O$******** ******@TK2MSFTN GP12.phx.gbl... Hi all and thanks in advance,
I am stuck! I can't figure out how to identify which button was clicked on my ASP.NET page in the PostBack event? So what I am trying to do
is to is to have an if statement like as follows in the PageLoad:
The best solution I've found to this problem is to not do it.

Don't ask in Page_Load which control caused the PostBack. Instead, handle the postback event of each control:
private void btnSave_Click(o bject sender, EventArgs e)
{
// Action when Save clicked
}

private void btnCancel_Click (object sender, EventArgs e)
{
// Action when Cancel clicked
}
--
John Saunders
johnwsaundersii i at hotmail

Nov 18 '05 #6
Agreed ... you should be able to do everything you need in the PreRender
handler. Use button click handlers to set page properties and/or
members, and process them on PreRender.

When I first begun .NET development, my initial instinct was to load
controls on page load as well, but that soon proved to be a pain. Since
then, I started using PreRender, and never looked back. Seems as though
you are spending the extra effort, going outside of the framework
provided, to achieve something you could have accomplished much faster
using the intrinsic event handlers and processing postback data on
Prerender.

ib.

John Saunders wrote:
"Andy Z Smith" <An********@dis cussions.micros oft.com> wrote in message
news:A8******** *************** ***********@mic rosoft.com...
I have come across this problem before. Sometimes you need to know before


the event handler fires which button was clicked, particularly if you are
creating dynamic controls or something that needs to be in page_load based
on the button press.
The solution so far is to do a HttpContext.Cur rent.Request[] of the


buttons id. If the request comes back null, the button was not pressed. If
the Request comes back with the ID of the button (essentially just a marker
anyway) then it was that button that was pressed.
Example:
Page_Load:

// adding the button
Button oButton = new Button();
oButton.ID = "PRESSME1";
oCell.Control s.Add(oButton);
...
Somewhere else in PageLoad

...///testing for the button being pressed.
if (HttpContext.Cu rrent.Request["PRESSME1"] != null)
// the button was pressed. do something like add a dropdown list


orsomething.

Another tricky one is trying to tell if a DropDownList or Checkbox marked


as AutoPost has caused a postback without using event handlers. In this
case you can use the JavaScript that .NET creates and hijack the
"__event_target " form variable.
Do a request on the __EventTarget and whatever ID comes back is what


caused the postback --- if the postback was caused by a DropDown or CheckBox
or something that has AutoPost back. If a submit button caused the post
back the __eventtarget is empty but you can do a request of the button's ID
as described above.

I've yet to find a situation where I've needed to know in Page_Load what
control posted back. It's always been possible to allow the postback events
and postback data events to fire and then to process the results of those
events in later handlers, like in the PreRender event. I have found this to
be true even for cases where the entire control hierarchy is created
dynamically.

Also, the techniques you mention are very dependant on the specific
implementation of the current version of ASP.NET. The two underscores in
"__EVENTTAR GET" are an indicator that this is an internal,
implementation-dependant name, subject to change whenever they feel like it,
or just whenever they want to play with your mind...

Nov 18 '05 #7
milimetric
1 New Member
Whereas I agree that __EVENTTARGET is subject to change in later versions, I disagree that the _need_ to know what triggered a PostBack doesn't exist.

On a complex form, you've got to worry about stuff like that. Take the following situation: you've got a checkbox and a button in a repeater. The CheckBox can only AutoPostBack. It can not generage the repeater_ItemCo mmand event. On the other hand, the button fires the ItemCommand event.

Therefore, if you set up a handler for the checkbox autopostback, when you click the button that handler will also get called. If your button relies on state that the checkbox handler changes, then you've got an inconsistent state by the time the ItemCommand event gets triggered.

Therefore, the Request[buttonId] method is very good at figuring out what's going on before processing things in PageLoad. However, say button1 is your Button object, you have to use Request[button1.UniqueI D] instead of Request[button1.ID] or Request[button1.ClientI D]. Use UniqueID because this is what gets registered to the Request object if the button1 object is nested inside repeaters or other parent objects on your form.
Apr 21 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1687
by: Kurt Watson | last post by:
I’m having a different kind of problem with Hotmail when I sign in it says, "Web Browser Software Limitations Your Current Software Will Limit Your Ability to Use Hotmail You are using a web browser that Hotmail does not support. If you continue to use your current browser software we cannot guarantee that Hotmail will work correctly for...
7
2371
by: Alan Bashy | last post by:
Please, guys, In need help with this. It is due in the next week. Please, help me to implement the functions in this programm especially the first three constructor. I need them guys. Please, help me. This was inspired by Exercise 7 and Programming Problem 8 in Chapter 3 of our text. I have done Exercise 7 for you: Below you will find the...
7
3581
by: x muzuo | last post by:
Hi guys, I have got a prob of javascript form validation which just doesnt work with my ASP code. Can any one help me out please. Here is the code: {////<<head> <title>IIBO Submit Page</title> </head> <style type="text/css">
7
3259
by: tyler_durden | last post by:
thanks a lot for all your help..I'm really appreciated... with all the help I've been getting in forums I've been able to continue my program and it's almost done, but I'm having a big problem that I believe if it's solved, the remaining stuff is easy... my full program until now is here: http://www.geocities.com/tom4_h4wk/progmail.zip the...
23
3241
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application to create certain textboxes, labels, and combo boxes? Any ideas would be appreciated. Thanks
13
2126
by: sd00 | last post by:
Hi all, can someone give me some coding help with a problem that *should* be really simple, yet I'm struggling with. I need the difference between 2 times (Target / Actual) However, these times will fall somewhere between a Start & End time Further more, there will be Break & Lunch times between Start & End. Example... Start 08:00 Break...
1
54477
PEB
by: PEB | last post by:
POSTING GUIDELINES Please follow these guidelines when posting questions Post your question in a relevant forum Do NOT PM questions to individual experts - This is not fair on them and we instruct our experts to ignore any such PMs completely Be sure to give the version of Access that you are working with and the Platform and OS if...
0
3036
by: 2Barter.net | last post by:
newsmail@reuters.uk.ed10.net Fwd: Money for New Orleans, AL & GA Inbox Reply Reply to all Forward Print Add 2Barter.net to Contacts list Delete this message Report phishing Show original
6
3295
by: jenipriya | last post by:
Hi all... its very urgent.. please........i m a beginner in oracle.... Anyone please help me wit dese codes i hv tried... and correct the errors... The table structures i hav Employee (EmpID, EmpName,DeptID,DateOfJoin, Sal, Addr) Finance (EmpID, Sal) Club (Clubname, EmpID, Fee, DateOfJoin) Leave (EmpID, Date) Department (DeptID, DeptName,...
5
2295
by: tabani | last post by:
I wrote the program and its not giving me correct answer can any one help me with that please and specify my mistake please it will be highly appreciable... The error arrives from option 'a' it asks for user name, check in the system but does not return the correct answer please help me with it. or if you have better way of doing it would you...
0
7518
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7446
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7715
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7469
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7808
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5087
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1935
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.