Hi
In Asp.net form I have dynamically generated buttons, every button submits a form to, is there a way to get which button was submit the form in page load event?
views:
355answers:
4
A:
Use CommandArgument property to determine which button submits the form.
Edit : I just realized, you said you need this at PageLoad, this works only for Click server side event, not for PageLoad.
Canavar
2009-10-08 10:26:57
And anyway, the CommandArgument does not contain a reference to the button, only the value for CommandArgument set in the button.
Tor Haugen
2009-10-08 10:44:32
ok, the when programmer dynamically generates the button, he can set the commandargument parameter as well, right ?
Canavar
2009-10-08 10:47:49
Oh yes, and that is probably a better idea if you ask me.
Tor Haugen
2009-10-08 11:09:37
A:
The sender argument to the handler contains a reference to the control which raised the event.
private void MyClickEventHandler(object sender, EventArgs e)
{
Button theButton = (Button)sender;
...
}
Edit: Wait, in the Load event? That's a little tricker. One thing I can think of is this: The Request's Form collection will contain a key/value for the submitting button, but not for the others. So you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
Button theButton = null;
if (Request.Form.AllKeys.Contains("button1"))
theButton = button1;
else if (Request.Form.AllKeys.Contains("button2"))
theButton = button2;
...
}
Not very elegant, but you get the idea..
Tor Haugen
2009-10-08 10:30:39
yea I know,but I need it on page load, event is called after page load
ArsenMkrt
2009-10-08 10:41:08
@ArsenMkrt : Sorry I don't ask you my previous question. Buttons are not posted to server in Request.Forms collection. I just wanted to inform Tor.
Canavar
2009-10-08 10:52:34
@Canavar: Not all of them, no, but the submitting one is. The key is the ID, and the value is the text. I tested my code. Did you?
Tor Haugen
2009-10-08 11:13:47
And what's with the downvote, I answered the question, didn't I (whine whine ;-)?
Tor Haugen
2009-10-08 11:14:42
+1
A:
protected void Page_Load(object sender, EventArgs e) {
string id = "";
foreach (string key in Request.Params.AllKeys) {
if (!String.IsNullOrEmpty(Request.Params[key]) && Request.Params[key].Equals("Click"))
id = key;
}
if (!String.IsNullOrEmpty(id)) {
Control myControl = FindControl(id);
// Some code with myControl
}
}
DreamWalker
2009-10-08 11:25:48
A:
This won't work if your code is inside a user control:
Request.Form.AllKeys.Contains("btnSave") ...
Instead you can try this:
if (Request.Form.AllKeys.Where(p => p.Contains("btnSave")).Count() > 0)
{
// btnSave was clicked, your logic here
}
Wagner Danda da Silva
2010-08-24 17:00:25