Tuesday 22 May 2007

Opening a new window with a linkbutton control

I couldn't do it, and it turns out that lots of other people can't do it either.

They tried to set the navigateurl attribute to the url they want, and then when they tried to open the link in a new window, they got a load of javascript in the address bar and no link.

There is a legitimate way around this, but it involves extending the linkbutton, which I didn't have time to do.

If you do want to do it though, you should try the 4guysfromrolla article, because it does give quite a nice explanation.

If you want a quick workaround, I suggest that you do the following:

Swap your linkbutton link with a regular anchor tag.


<a href="#" id="linkTag" runat="server">This is an example link</a>


That'll be enough for your aspx page. The runat tag and id tags are new and allow you to get to the control from the code-behind.

If you're modifiying the control within a datalist or a datarepeater, you'll need to use findcontrol to get hold of it. If you do, you'll need this code:

Dim link as new htmlAnchor

link = e.item.findControl("linkTag")

The above creates a new anchor tag control and finds the one on your page.

However, if you're just accessing it within a regular function that isn't binding data, you can assign the bits you need like this:

linkTag.HRef = "http://karlitr0s.blogspot.com"
linkTag.innerText = "Karl's Blog"
linkTag.title = "Karl's Blog"
linkTag.target = "_blank"

The innertext tag is for labelling your link.
The href tag points to where you need to go.
The target tag is the html equivalent, and opens up the new window for you.

Doing it this way instead of using Javascript:window.open('') in the href tag means that you don't get your original page from displaying [object] or whatever your browser does when it doesn't understand where it's going within .NET.

Definately the quickest and easiest way around it, but if you have to use external links a lot in your application or you have to utilise the postback as well, you're probably better off extending the linkbutton.

No comments: