How to prevent a GridView's ButtonField from doing a postback when clicked?

R

Rob Roberts

Is there any way to prevent a ButtonField in a GridView from doing a
postback when clicked? I want to use my own onclick handler to call
window.open('SomePage.aspx') to display a page in a new browser window when
the button is clicked.

I tried doing this in the RowCommand postback event by doing this in the
event handler:

Response.Write("<script>window.open('SomePage.aspx');</script>");

This works, but has an undesirable side effect: It adds the page to the
history list every time one of the button fields is clicked. So for example
if the user clicked three button fields to show three popup windows, and
then wants to return back to the previous page, he must click the Back
button four times instead of just once.

I'm using the RowDataBound event to add my own onclick event handler to the
button's attribute collection, but I can't figure out how to get rid of the
"javascript:__doPostBack(...)" that asp.net automatically adds. I tried
using button.Attributes.Remove("onclick") before adding my own onclick event
handler, but the "javascript:__doPostBack(...)" ends up still being there.

Any ideas on how to stop the postback?

Thanks in advance,
--Rob Roberts
 
B

Bruno Piovan

Hi Rob,
add an attribute OnClick, with the value of window.open, and add a "return
false;" as well, return false will cause the post back to be canceled,

example,

button.Attributes.Add("OnClick", "window.open('SomePage.aspx'); return
false;");

* for OnClick, you can use the property OnClientClick (Framework 2.0), so it
would be:

button.OnClientClick = "window.open('SomePage.aspx'); return false;";

** if you use response.write with the javascrip code to show the popup
window, most anti-popup will block it...

Bruno


"window.open('SomePage.aspx'); return false;"
 
R

Rob Roberts

Bruno,
add an attribute OnClick, with the value of window.open, and add a "return
false;" as well, return false will cause the post back to be canceled,

example,

button.Attributes.Add("OnClick", "window.open('SomePage.aspx'); return
false;");

Thanks for the tip of adding "return false;"! I solved the problem by
changing the ButtonField to a TemplateField and then setting the cell's Text
property to a string containing the necessary html to create a button with
an appropriate onclick event handler. But it looks like it would have been
easier to stick with the ButtonField and add "return false;" to the end of
the onclick event handler, as you showed. I'll try that next time.

Thanks again!
--Rob Roberts
 

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

Top