Programatically setting OnClick handler for asp:Button (how to do?)

  • Thread starter Thread starter Richard Morse
  • Start date Start date
R

Richard Morse

Hi! I have an aspx that I've created which has an asp:Button in it. I
would like to be able to change the OnClick handler at runtime
(basically, I want this form to either edit or create a record, and I
want to change the procedure it calls depending on what it should be
doing). However, apparently the .OnClick member is read only?

(Sample:)

<script language="jscript">
function do_edit() {
...
do_action_btn.Text = "Save";
do_action_btn.OnClick = "do_update";
}
....
</script>
<html>
<head>
</head>
<body>
<form id="page_form" runat="server" />
...
<asp:Button id="do_action_btn" runat="server" />
...
</form>
</body>
</html>

----------

Alternately, if the above isn't possible, I can do something with
CommandButtons, but without a repeater/datagrid/datalist, I'm not sure
where to put the "OnItemCommand" property...

Thanks muchly,
Ricky Morse
 
I haven't had much luck re-using buttons over multiple
post backs. There is a solution, however. You can use a
number of asp:Panels to hold sets of buttons (or whatever
you need to change between post backs). Create a Panel
holding the first "Edit" button, and a second Panel
holding the "Save" button with visibility=false. In
Edit_OnClick, set edit_panel.visibility=false and
save_panel.visibility=true. Obviously, you will need
different OnClick handlers for each button.

That's not exactly what you asked for, but it can
sometimes be a little cleaner than re-using buttons and
eventhandlers.

hth,
Matt
 
submit/image buttons have a value they post back. just change the value in
client script, and check the value on the server side on the onclick event.


function do_edit() {
var btn = document.getElementById('do_action_btn');
...
btn.value = "Save";
}

-- bruce (sqlwork.com)
 
In VB.NET, you can dynamically tie events to event handlers with the
"AddHandler" and "RemoveHandler" statement. In your case, you can use the
"RemoveHandler" to remove the old event handler and then use "AddHandler" to
tie the button to a different event handler.

See info onAddHandler:
http://msdn.microsoft.com/library/d...en-us/vblr7/html/vastmAddHandlerStatement.asp
See info on RemoveHandler:
http://msdn.microsoft.com/library/d...us/vblr7/html/vastmremovehandlerstatement.asp

Corey O'Mara
MCSD.NET, MCT
 
Back
Top