dotNetChris @ Marisic.Net

November 4, 2008

C# ASP.NET Response.Redirect Open Into New Window

Filed under: Programming — Tags: , , , — dotnetchris @ 12:37 pm

UPDATED: 11/04/2008 (see bottom of post)

So I came across the day the desire to have a button open up a new window instead of just using an anchor tag, as usual I run the idea through google and mostly come back with responses saying it’s not possible that way, or to add javascript to the page to capture events. Not quite the solution I was looking for after doing some more searching I came across a javascript solution that would work but wasn’t elegant at all which led me to ponder on adapting it to be cleaner and this is what I came up with.

<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry"

OnClick="btnNewEntry_Click" OnClientClick=" ='_blank';"/>

protected void btnNewEntry_Click(object sender, EventArgs e)

It even works using Server.Transfer. There you have it a simple unobtrusive solution to handle Response.Redirect into a new window without needing to add any javascript tags and only take advantage of the OnClientClick event on the button itself.

Update 10/22/2008:

I’d like to thank one of my commenters, Dan, for his solution for accessing the form inside a master page on the child page level.



This code will dig down into the controls collection and find your form and allow you to get access to the client id so you can be sure you have proper naming of it for the javascript to function correctly. Make sure you replace “form1″ with whatever you have your parent form id=”name” set to inside your Master’s page markup.

Update 11/04/2008:

If you have multiple buttons on a single page and only want a specific button to launch into a new windows and want the rest to stay on the current form make sure you decorate your other buttons like

<asp:Button ID="btnStayOnPage" runat="Server" CssClass="button" Text="Stay here"

OnClick="btnStayOnPage_Click" OnClientClick=" ='_self';"/>

protected void btnStayOnPage_Click(object sender, EventArgs e)
   //Do normal code for postback


kick it on

About these ads


  1. I have a Link button on my page with PostBackURL set to a page called PX.aspx. I have set the OnClientClick to’_blank’, but my page does not open in a new window. Is there anything else i should look out for.


    Comment by kangaroo — July 6, 2008 @ 8:33 am

  2. Take a look at the source html on your page and make sure the form name is actually aspnetForm and not a different id.

    Comment by dotnetchris — July 6, 2008 @ 1:29 pm

  3. I agreed with you

    Comment by Optoritops — August 3, 2008 @ 2:04 am

  4. [...] – bookmarked by 2 members originally found by etiopica on 2008-07-19 C# ASP.NET Response.Redirect Open Into New Window – [...]

    Pingback by Bookmarks about Asp — August 6, 2008 @ 7:15 am

  5. This is great! Such a headache solved.

    Comment by Justin — September 3, 2008 @ 10:50 pm

  6. Always glad to hear one of my posts benefited another person!

    Comment by dotnetchris — September 4, 2008 @ 7:06 am

  7. Thanks a lot. It worked wonders for me

    Comment by Pankaj — September 15, 2008 @ 12:46 am

  8. Good to hear Pankaj!

    Comment by dotnetchris — September 15, 2008 @ 12:58 am

  9. Chris I have a doubt.
    Actually i am passing paramter from one page to another to display report. If user does not sends a valid paramter the window should close informing the user of the error. My Code is

    MessageBox.Show(“Please select the component to view report”, “Report Data”, MessageBoxButtons.OK, MessageBoxIcon.Error);

    but i find that it opens two windows instaed of single window in case of user not selecting a valid paramter. can u suggest me on this.

    Thanks for the help earlier.

    Comment by Pankaj — September 15, 2008 @ 5:05 am

  10. Hi Chris,
    This is happening because of auto postback property of a dropdown list control as i am using that. But i need to display report based on multiple conditions and each condition depends upon the previous one. Eg.
    Base control holds all the base name.
    Depending upon base, location names are listed.
    Depending upon Location Dept names are to displayed. etc.

    Here each time the user selects invalid value a window opens upon postback. how can i overcome this.

    My code is written upon button click

    if (ddlBase.SelectedIndex == 0)
    lblMessage.Text = “Select the Base”;
    MessageBox.Show(“Select The Base”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    else if (ddlLocation.SelectedIndex == 0)
    lblMessage.Visible = true;
    lblMessage.Text = “Select the Location”;
    MessageBox.Show(“Select The Location”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    else if (ddlDepartment.SelectedIndex == 0)
    lblMessage.Visible = true;
    lblMessage.Text = “Select the Department”;
    MessageBox.Show(“Select The Department”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    else if (ddlComponent.SelectedIndex == 0)
    lblMessage.Visible = true;
    lblMessage.Text = “Select the Component”;
    MessageBox.Show(“Select The Component”, “Conditional Report”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    string strComponet = string.Empty;
    string strDeptName = string.Empty;
    string strLocName = string.Empty;

    strComponet = ddlComponent.SelectedValue;
    strDeptName = ddlDepartment.SelectedValue;
    strLocName = ddlLocation.SelectedValue;

    Response.Redirect(“ConditionalReport.aspx?Component=” + strComponet + “&Dept=” + strDeptName + “&Loc=” + strLocName);


    and on client click

    OnClientClick=” =’_blank’;”

    I will be obliged if you can help me.

    Thanks for your efforts and help

    Comment by Pankaj — September 15, 2008 @ 5:37 am

  11. What I’d recommend is checking the drop down list for a similar event to OnClientClick probably OnSelectedIndexChanged if your using the built in dropdownlist web control and set on that method

    OnSelectedIndexChanged=” =’_self’;”

    This should reset the form target for the drop down list changes that it will post those to the current window and only open the new window when you click the button instead of causing all your posts back to open in a new window. My other suggestion would be if that doesn’t solve it is to take off auto post back on the dropdownlist and set the logic that you have in the change event to be ran inside the button click method instead and have it do it’s validation/selection operations there.

    Comment by dotnetchris — September 15, 2008 @ 8:28 am

  12. Thanks Chris for your much valued suggestions and efforts. I will try the same. Thanks a lot.

    Comment by Pankaj — September 16, 2008 @ 2:26 am

  13. Hi,

    This is really gud, worked for me.

    Thanks a lot

    Comment by Arthi — September 16, 2008 @ 2:47 am

  14. Hi Chris,
    Can u suggest me on this:
    I need to generate a text file with some data in it. which is working fine for me.
    My question is,
    how can i save the text file on the client’s hard drive instead of saving it on the server.

    Thanks For the Help and suggestion

    Comment by Pankaj — September 23, 2008 @ 8:07 am

  15. Pankaj,

    Basically what you want to do is when they click the link to download the text file to redirect them to an aspx page that is basically entirely blank similar to

    In the code behind you will need to handle getting the data to display the text file then to render it out to the window do something similar to

    byte[] _content = txtDocumentBinary;

    Response.Buffer = false;
    Response.ContentType = “application/octet-stream”; Response.AddHeader(“Content-Disposition”, string.Concat(“inline; filename=”, _fileName,”.txt”));
    Response.AddHeader(“accept-ranges”, “bytes”);
    Response.AddHeader(“Content-Length”, _content.Length.ToString());
    Response.OutputStream.Write(_content, 0, _content.Length);

    Comment by dotnetchris — September 24, 2008 @ 1:30 pm

  16. In a datagrid an entire column is of LinkButton type.
    As you mentioned, I have added the property onclientclick

    <asp:LinkButton ID=”LinkButton1″ runat=”server”
    CommandArgument=” CommandName=”event_id_link”
    onclientclick=”’_blank’;” >

    In my RowCommand event of the Gridview, code goes as

    Response.Redirect(“~/CRM/et.aspx?event_id=” + Session["EventID"].ToString());

    Regardless does not open a new page with details.
    Am I doing anything wrong, any suggestions will be helpful

    Thanks in advance

    Comment by SP — September 25, 2008 @ 11:06 am

  17. SP

    I believe this is an issue of browser interpretation of Link Buttons. Link buttons aren’t true buttons they are just anchor tags with hrefs. I do not believe link buttons have an OnClick which is what OnClientClick will become when it is rendered out. I believe in internet explore it will acknowledge the OnClick event even though it’s invalid but browsers that follow HTML specifications correctly will ignore it.

    Try switching this over to a regular button and see if it works, also double check your pages actual source in the browser to verify that the form id is actually named “aspnetForm” and not assigned another value.

    Comment by dotnetchris — September 25, 2008 @ 12:03 pm

  18. Thanks Chris,
    I am using Message Box in my application ( version 2.0)
    The Syntax is :-

    MessageBox.Show(“No Matching Record Exists…”, “Information”, MessageBoxButtons.OK, MessageBoxIcon.Information);

    But i am getting a the following error mentioned below.

    Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

    Can you suggest me any solution on this.

    Thanks a lot chris, for helping me each time.
    I am obliged.


    Comment by Pankaj — September 30, 2008 @ 5:05 am

  19. Pankaj,

    MessageBox.Show is for windows forms applications only that’s why you’re getting that error message. The simplest way to acheive that is with the javascript Alert(“your message here”) method. Creating dialogs for web applications is an overly complex task for some reason.

    Take a look at this for a better solution than the javascript alert.

    Comment by dotnetchris — September 30, 2008 @ 8:17 am

  20. Hi Chris,
    There ssems to be some problem with this web link.

    It is opening but not able to download or view demo.

    But anyways, thanks a lot for your effort.


    Comment by Pankaj — October 3, 2008 @ 5:23 am

  21. Pankaj if you would rather it display as a save this file as dialog when they click the link change

    Response.AddHeader(”Content-Disposition”, string.Concat(”inline; filename=”, _fileName,”.txt”));


    Response.AddHeader(”Content-Disposition”, string.Concat(”attachment; filename=”, _fileName,”.txt”));

    Comment by dotnetchris — October 3, 2008 @ 6:59 am

  22. Is there any way to control the size of this new window when we are using OnClientClick=” =’_blank’;”?

    Comment by Shafiq — October 8, 2008 @ 11:14 am

  23. Chris,

    This worked perfectly, and I’d almost given up that this could be done in .NET! Thank you so much.

    bob :)

    Comment by bob — October 10, 2008 @ 10:55 am

  24. That’s great to hear Bob!

    Shafiq, that I’m a little hesitant to say, I think you might be better off on the page that it pops up to have inside the new page javascript to resize the window to the size you want. I think that would be the best option.

    Comment by dotnetchris — October 10, 2008 @ 12:00 pm

  25. Hi Chris,
    when i am trying to access a report from client, it is giving me the following error.

    Can you please suggest me something for this. Do i need to make any changes in web.config file. I have implemented forms authentication.

    The Error is as follows:-

    Access to the path ‘D:\ReportsData\objdsShowData.xml’ is denied.

    Exception Details: System.UnauthorizedAccessException: Access to the path ‘D:\ReportsData\objdsShowData.xml’ is denied.
    To grant ASP.NET access to a file, right-click the file in Explorer, choose “Properties” and select the Security tab. Click “Add” to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.

    Source Error:

    Line 37: strTableName = classInventory.GetTableName(strComponentName);
    Line 38: objdsShowData = classInventory.GetReportData(strTableName);
    Line 39: objdsShowData.WriteXml(“D:\\ReportsData\\objdsShowData.xml”);
    Line 40: rptDoc.Load(Server.MapPath(@”SystemsData.rpt”));
    Line 41: rptDoc.SetDataSource(objdsShowData.Tables["Table"]);

    Source File: d:\Inventory\Report.aspx.cs Line: 39

    Thank You for sharing your knowledge all the way through. I am obliged.


    Comment by Pankaj — October 13, 2008 @ 5:19 am

  26. Pankaj,

    The error you are receiving is a windows security error. The ASP.NET user account does not have access to that folder. There are a few ways to solve this

    1. give the ASP.NET account privileges to read (and write if needed) to that folder.
    2. Move that folder inside virtual directory folder
    3. Set up WindowsImpersonation and use an account that has accessible privileges to that folder, one of my previous posts deals with the WindowsImpersonation that I wrote about my TaskScheduler.

    Comment by dotnetchris — October 13, 2008 @ 7:23 am

  27. Hi Chris,
    I have one small doubt If i enable WindowsImpersonation will my forms authentication be changed to windows authentication.
    Actually i am new to this section. I have never face this before so i am confused.
    How do i give the necessary permissions.
    I have created virtual directory in the IIS. And my application is already under this folder in the IIS.

    Thanks a lot for guiding me.


    Comment by Pankaj — October 14, 2008 @ 12:30 am

  28. Pankaj,

    Take a look at the top portion of the article basically outlines the same problem you are facing, ASP.NET is trying to access a resource it doesn’t have permission to. Towards the end of the article it shows a walkthrough for adding ASP.NET’s windows account to permissions on a folder which is what you want to do either for your folder with the .XML file or just specifically on the .XML file if you will not create any new files in that directory and will only read from the .XML files.

    Keep in mind every folder you add permissions to for ASP.NET there’s another area that potentially could be exploited if the machine is attacked. Generally the risk is fairly low especially if you are only granting read/write access to individual files. I would very strongly recommend NEVER grant execute access for any folders to ASP.NET manually. The risk there could become very high.

    I hope that helps!

    Comment by dotnetchris — October 14, 2008 @ 11:14 am

  29. Thanks a lot for the immense and much needed help Chris.
    I am really grateful to you.
    Hat’s Off to your knowledge.


    Comment by Pankaj — October 15, 2008 @ 1:02 am

  30. Hello Chris,
    I am trying this with a Crystal Reports Browser.
    No new window though. I have been looking for something this elegant to work but perhaps I am missing a key element?

    protected void LoadReport(object sender, EventArgs e)
    // This tries to find the report in the folder when you click open
    // The report should have the filename as the name of the folder it’s in with -parameters, -dynamic, etc on the end
    // This function will go through these filenames in order and redirect to the first it finds
    // If it doesn’t find any, it returns an error message to the description textbox
    Description.Text = “No report found!”;

    protected void FindReport(string filename)
    // Creates the filename from the folder name and the additional -parameters, etc extension
    string rname = ReportsBrowser.Items[ReportsBrowser.SelectedIndex].Text;
    string[] titles = rname.Split(SplitLbl.Text.ToCharArray());
    foreach (string t in titles)
    rname = t;
    string favdesc = “e:Protrak/WebApps/Reports/CrystalReports/” + ReportsBrowser.SelectedValue + “/” + rname + filename;
    if (File.Exists(ReportsBrowser.SelectedValue + “/” + Path.GetFileName(ReportsBrowser.SelectedValue) + filename) == true)
    // Loading a project from the reports browser
    Response.Redirect(“http://protrak/Reports/CrystalReports/” + ReportsBrowser.SelectedValue.Remove(0, 41) + “/” + Path.GetFileName(ReportsBrowser.SelectedValue) + filename);
    if (File.Exists(favdesc) == true)
    // Loading a project from the favorites
    Response.Redirect(“http://protrak/Reports/CrystalReports/” + ReportsBrowser.SelectedValue + “/” + rname + filename);


    Comment by Chris — October 16, 2008 @ 1:58 pm

  31. form id=”reports” runat=”server”
    asp:Button ID=”LoadButton” runat=”server” Text=”Open Report” OnClick=”LoadReport” OnClientClick=”’_blank’;”/

    Comment by Chris — October 16, 2008 @ 2:01 pm

  32. @Chris

    When you click the button does it execute your code correctly and do a Response Redirect but transfer the page inside the current window?

    Also did you verify in the browser by going to view source that form id is actually reports and ASP.NET didn’t override it and replace it with another value?

    Do you have javascript enabled?

    Comment by dotnetchris — October 17, 2008 @ 9:42 am

  33. @Pankaj

    I’m always glad to share my knowledge because I know there’s always so much more I don’t know yet and the only way to grow as a developer is share your knowledge and learn from others.

    Comment by dotnetchris — October 17, 2008 @ 10:13 am

  34. OnClientClick=” =’_blank’;”

    It works great, but how can I access form1 if its in master page? Please help

    Comment by Dan — October 17, 2008 @ 11:51 am

  35. Thanks for the response Chris, it looks like I do according to the source:

    form name=”reports” method=”post” action=”Reports.aspx” id=”reports”

    script type=”text/javascript”>


    Comment by Chris — October 17, 2008 @ 1:07 pm

  36. script type=”text/javascript”

    var theForm = document.forms['reports'];
    if (!theForm) {
    theForm = document.reports;
    function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    theForm.__EVENTTARGET.value = eventTarget;
    theForm.__EVENTARGUMENT.value = eventArgument;


    Comment by Chris — October 17, 2008 @ 1:08 pm

  37. Something odd and I am not sure which character it is but the line containing the reports button is registering an internet explorer error for invalid character.

    input type=”submit” name=”LoadButton” value=”Open Report” onclick=”’_blank’;” id=”LoadButton” style=”font-family:Arial;font-size:Small;font-weight:bold;”

    Comment by Chris — October 17, 2008 @ 1:21 pm

  38. Chris

    It could be issues with ‘_blank’ wordpress seems to change it to an unusual type of apostrophe. I would recommend retyping the lines out by hand in visual studio that you changed on the button tag and that might fix the issue. I had considered that as a possibility

    Comment by dotnetchris — October 17, 2008 @ 4:45 pm

  39. Dan,

    What I would recommend doing is exposing a public get property your master page for WhatEverYourFormNameIs.ID, then in your child pages on the PageLoad event add inside your if(!Page.IsPostBack) wrapper statement

    btnSomeSubmitButton.OnClientClick = string.Format(“{0}.target=’blank’;”, ((YourMasterPageTypeName)this.Master).FormNameID);

    OR you could expose a public method like GetFormTargetNewWindowButtonScript() inside your master page and do something like

    public string GetFormTargetNewWindowButtonScript()
    return string.Concat(WhatEverYourFormNameIs.ID,”.target=’blank’;”);

    and inside your child page on load again

    btnSomeSubmitButton.OnClientClick = ((YourMasterPageTypeName)this.Master).GetFormTargetNewWindowButtonScript();

    This was all coded freehand in my response window so it’s possible I have a syntax error in one of these lines but it should be clear what my intent was. Let me know if either of these solutions works out for you!

    Comment by dotnetchris — October 17, 2008 @ 4:52 pm

  40. Hi ,
    I also have a same problem but let me tell you where i got problem.
    1) i have a master page file (masterpage.master) and there is a …elements ..
    2) I hae a content page where I have a button and i use your above script as below but i did not find a form (.Form1.ID) from property list after closing second last parantesis.

    button1.OnClientClick = string.Format(”{0}.target=’blank’;”, ((masterpage.master)this.Master).

    I did not find the form and neither their ID. I think that should be like below but did not find.

    button1.OnClientClick = string.Format(”{0}.target=’blank’;”, ((masterpage.master)this.Master).Form1.ID

    Comment by nam — October 17, 2008 @ 6:16 pm

  41. Thanks a lot.

    I solved my problem with this line in the page load

    Button1.OnClientClick=string.Format(“{0}.target=’_blank’;”, ((HtmlForm)Page.Master.FindControl(“form1″)).ClientID);

    It was a great Idea by you. Thanks again:)


    Comment by Dan — October 17, 2008 @ 7:37 pm

  42. Hi Chris,
    can you please suggest me how can i access ftp return code using C#.
    Based on the return code i need to call a procedure.


    Comment by Pankaj — October 20, 2008 @ 5:53 am

  43. Dan,

    Thanks for posting your solution, you got the exact idea I was going for. It also points out one of my biggest annoyances with ASP.NET web forms is the layers of obfuscation that are forced upon the IDs of elements. That’s one of things I think is great about ASP.NET MVC is the much stronger level of control you have over your true html output.


    Take a look at Dan’s comment.

    Comment by dotnetchris — October 22, 2008 @ 2:30 pm

  44. Hello, first of all sorry about my english.

    It works fine form me, but i have got a problem:
    I click my button and a window opens in a blank page. All correct.
    I close this window, i try to click another button, and another button try to do the same as the button which has got target blank. And the new button has its own code. It execute its code and then do the postbackurl, but this other button has not got this property!!

    Thank you!

    Comment by mahoni — November 4, 2008 @ 8:04 am

  45. i have to say that i use postbackurl because i have got pass to another page hidden values

    Comment by mahoni — November 4, 2008 @ 8:07 am

  46. Mahoni,

    I’m not sure I understand your question, is the problem that the 2nd button causes a new window to display when you want the 2nd button to stay in the original window?

    If this the case read the bottom of my post as I updated for it, otherwise please clarify and I’ll try to help.

    Comment by dotnetchris — November 4, 2008 @ 4:24 pm

  47. Chris, Thank you so much. I have been doing it all wierd ways by creating an iframe and opening the new window in it. Glad I saw your post. Better late than never :) Thanks once again.

    Comment by Swap — November 5, 2008 @ 12:52 pm

  48. Swap,

    I’m glad I was able to help, thanks for letting me know!

    Comment by dotnetchris — November 5, 2008 @ 1:50 pm

  49. Chris,
    This is great, and helped me alot. I wanted to add one thing…

    If you are using this logic inside of an ASP.NET UpdatePanel, you need to add a postback trigger for the control that contains this code.


    Comment by Jesse — December 9, 2008 @ 12:26 pm

    • Jesse,

      I’m always glad to hear that my blog helped you, and yes you’d be right since the button does need to do a full post back for this to work so it fully makes sense that you need to add the trigger settings for it if you’re using any type of AJAX.


      Comment by dotnetchris — December 9, 2008 @ 2:56 pm

  50. Thanks Chris! What a simple solution to a problem I have dealt this since switching over to the .net platform.

    Comment by Brian — December 12, 2008 @ 2:13 pm

  51. This saved me a “boat-load” of time and headaches. Most sites said it couldn’t be done. Thanks.

    Comment by TonyBlack — December 17, 2008 @ 11:27 pm

    • I know how you felt Tony, I went through that on my road to the creation of this blog post!

      Comment by dotnetchris — December 18, 2008 @ 12:19 am

  52. protected void btnNewEntry_Click(object sender, EventArgs e)

    Comment by arun — January 2, 2009 @ 1:52 am

  53. I had been trying to open a report in a new browser window after the report information had been validated, sorted (yada yada),and then redirect the origional page back to the Reports generating page.

    I dont know if my code will help anyone else…. But here…

    Response.Write(“‘../Reports/Sales.aspx’,’_blank’);”); // The Popup URL
    Response.Write(“‘../SiteAdmin/Reports.aspx’,’_self’);”); // The Redirect URL

    Some people prob have really fancy ways of doing it, but this way works for me!

    Happy Coding!


    Comment by dev.Net Rob — January 8, 2009 @ 10:50 am

  54. Ok Hurray… Lets try that again shall we…

    Response.Write(“”); // Should say Response.Write(“script”); with
    Response.Write(“”); // Should say Response.Write(“/script”); with

    Sorry bout that ppl…

    Comment by dev.Net Rob — January 8, 2009 @ 10:53 am

    • Thanks for your comment Rob, that is definitely a viable way to do this also but my goal was to avoid as much as possible needing to either code or inject javascript into the page but it’s always good to see another way that no one else has pointed out yet since it might help someone later.

      Comment by dotnetchris — January 8, 2009 @ 4:47 pm

  55. Thanks a lot
    one of my most unsolved puzzle is got the crystal clear answer.

    Comment by swati — March 2, 2009 @ 6:08 am

  56. Hello,

    I tried the as

    Button is inside the gridview and grid under the UpdatePanel.
    It does not open the new window, Can anybody tell me what I am missing or I can’t do it.

    Comment by desivir — March 23, 2009 @ 10:19 pm

  57. Sweet! Solved my issue instantly.

    Comment by Mick — April 9, 2009 @ 4:29 am

  58. Hi all,
    I had the problem of opening a popup on a Response.Redirect instruction from a page which used an AJAX-enabled masterpage (with a ScriptManager and an UpdatePanel). I tried the above solutions but they didn’t work, apart from the javascript one. I solved my problem using javascript on just one line of code in the button-click handler method. Here it is:

    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "uniqueKey" + DateTime.Now, "'MyUrl.aspx','_blank');", true);


    Comment by Er — June 23, 2009 @ 7:46 am

  59. Hey, worked like a charm. Thanks a lot for saving a time…. From where you got that??

    Comment by Gagandeep Tandon — July 2, 2009 @ 9:55 am

  60. This is fantastic, worked brilliantly!

    OnClientClick=” =’_blank’;”


    Comment by Chad — October 6, 2009 @ 10:38 pm

  61. oops, here is a challenge…

    i want it to SELECTIVELY open in a new window, don’t think this solution will work for that.

    I have a simple input box which is a search, on submit i search based on user input, if there is a match i want to redirect to a page in a new window, if there is not a match i want to stay on that page and show a panel.

    any ideas?


    Comment by Chad — October 6, 2009 @ 10:51 pm

    • Chad,

      If the case is you selectively want to do it, you’ll find it much easier to use Page.ClientScript.RegisterClientScript and just inject in a event.

      Comment by dotnetchris — October 7, 2009 @ 9:08 pm

  62. I can’t believe the solution was that simple. Thanks so much for your help!

    Comment by Reb — December 14, 2009 @ 5:59 pm

  63. Thx .Its great Help

    Comment by Hina — January 19, 2010 @ 7:02 am

  64. Hi Chris,

    Thanks for the posting. I have been trying for this since so many days. I had many image buttons on our website’s home page. When I use the target=’_self” it fixed the issue I was having.

    Comment by Triveni — June 1, 2010 @ 4:51 pm

  65. Very Good Job. Saved lot of time for me

    Comment by Somasekhar — June 24, 2010 @ 5:48 pm

  66. Thank you for the simple solution. I too found several “it can’t be done” posts before stumbling by this one.

    Comment by Morten — August 16, 2010 @ 8:30 pm

  67. I always use this code !

    String clientScriptName = “ButtonClickScript”;
    Type clientScriptType = this.GetType ();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager clientScript = Page.ClientScript;

    // Check to see if the client script is already registered.
    if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
    StringBuilder sb = new StringBuilder ();
    sb.Append (“”);
    sb.Append (“‘ ” + url + “‘)”); //URL = where you want to redirect.
    sb.Append (“”);
    clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());

    Comment by Abhishek Shrivastava — August 26, 2010 @ 6:21 pm

  68. Thanks Chris! Exactly what I needed. Very clean and simple too.
    Now on to the next problem…

    Comment by John — October 15, 2010 @ 7:53 pm

  69. Hi,

    With an asp linkbutton once the first click has been made the onclientclick command overwrites the onclick command, and thus i lose the link to run my command which is the whole point of using a linkbutton and not hyperlink. So this only works for first click and then is becomes a dead button.

    Comment by dave — October 29, 2010 @ 10:04 am

    • This was meant to work for submit buttons, for linkbuttons you can just set target=”_blank”, maybe.

      Comment by dotnetchris — December 1, 2010 @ 3:49 pm

  70. OnClientClick=” =’_blank’”

    showing error
    Microsoft JScript runtime error: ‘aspnetForm’ is undefined

    Comment by abuhurera asnari — April 26, 2011 @ 12:48 pm

    • You must have your form named something different than aspnetForm, that’s the default name. Take a look in the source of your page and see what form id = “” is set to

      Comment by dotnetchris — September 22, 2011 @ 8:37 pm

  71. Hi,

    I am in the sutuation where the open in a new page should be conditional, but should only be done when the button is clicked.
    Do you maybe have a clean solution?


    Comment by Daniel — May 4, 2011 @ 11:13 am

  72. OH ~! Thanks a lot

    Comment by oregano — August 9, 2011 @ 9:12 am

  73. thanx a lot ………………..
    OnClientClick=”’_blank’;” ………….worked like a charm

    Comment by Abhijith — August 18, 2011 @ 8:29 am

  74. It works for me :) superb. Thanks :)

    Comment by Chua Wen Ching — September 7, 2011 @ 10:44 am

  75. hello chris from france

    i use 2008

    i have several identical pages with datalist

    inside datalist i have declared a buttonimage in wich i declare a commandargument that is the link to a new page and a imageurl that is the url of the image



    in the code i have the following source

    Protected Sub DataPro_FicheClick(ByVal sender As Object, ByVal e As EventArgs)

    Dim ImgBtn As ImageButton = sender
    Dim Lnk As String = ImgBtn.CommandArgument


    End Sub

    it works for 4 pages but not for one

    when i look at the source code of the page i have the form id correct

    but i do not see the datalist as for the others

    on the web page the datalist exists

    when i click on the imagebutton it does not execute the target=’_blank’

    the difference with the other pages is that page is biggest

    on all the pages the events for the datalist are the same (selectedindex, itemdatabound) and the itemdatabounded event is in a commun module unedr app_code

    is it a bug of vb 2008 ?

    is there something to do in the web.config ?

    i hope that you can help me and maany thanks in advance

    Comment by Xvier BETOUX — September 13, 2011 @ 2:43 pm

  76. Hi Chris thanks for posting this. However, after I tried it, the new page opens but in the same window. What could have happened? I have read all the comments but none seemed to have experienced the same. Can you help? thanks again

    Comment by Carlos — September 22, 2011 @ 2:14 pm

  77. I know this is a very old post, but I just stumbled across it and the solution worked perfectly. THanks!

    Comment by Matt — November 22, 2011 @ 5:29 pm

  78. This took me far too long to do. Thank you, Dan’s addition helped me out.

    Comment by TedMint — January 3, 2012 @ 2:52 pm

  79. Why do I get the error?:

    Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.

    Comment by Maikol — January 17, 2012 @ 5:19 pm

    • I don’t know, that seems unrelated and seems like you have a specific issue either with your usage of MS Ajax or a control’s usage of MS ajax.

      Comment by dotnetchris — January 27, 2012 @ 6:48 pm

  80. It’s not worked if I use with updatepanel.
    How can I make it work?

    Comment by TU — March 12, 2012 @ 12:44 pm

  81. It’s not worked if I use with update panel. How can I make it work?

    I tried with the suggested code above
    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), “uniqueKey” + DateTime.Now, “‘MyUrl.aspx’,’_blank’);”, true);

    It’s still not worked.

    Thank you very much.

    Comment by TU — March 12, 2012 @ 12:53 pm

    • Make sure the scriptmanager is inside the update panel, and i think something like that should work. It’s possible a popup blocker is stopping it though, i guess.

      Comment by dotnetchris — March 12, 2012 @ 11:11 pm

  82. following code not working
    can any budy help to open a new window when I click on link button in grid view

    protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
    if (e.CommandName == “cmd”)
    string url = Server.MapPath(“~//Html\\abc.htm”);
    LinkButton lbtn = (LinkButton)GridView1.Rows[RowIndex].Cells[1].FindControl(“hypeno”);
    lbtn.Attributes.Add(“onClick”, “‘url’, ‘height=400,width=600′) return false”);

    Comment by Maddy — June 26, 2012 @ 10:38 am

    • In this scenario, you might need to use RegisterClientScriptBlock as you posted

      Comment by dotnetchris — August 23, 2012 @ 4:27 pm

  83. Try this code work for me !
    I hope this will work for u
    best luck!

    string file =”abc.html”;
    string url = “Http:\\Html/\\” + file;
    string strScript = “‘” + url + “‘,’_blank’)”;
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), “strScript”, strScript, true);

    Comment by Maddy — June 27, 2012 @ 12:41 pm

    • This will work but my goal was to avoid RegisterClientScriptBlock

      Comment by dotnetchris — August 23, 2012 @ 4:27 pm

  84. it is useful. it solved my problem. thank you.

    Comment by jeyavel — November 21, 2013 @ 4:38 pm

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at


Get every new post delivered to your Inbox.

Join 243 other followers

%d bloggers like this: