Things I’ve learnt from developing an ASP.NET application

Just another WordPress.com weblog

Hyperlink controls and data binding

leave a comment »

An application I’m working on at the moment needs to display a list of products and provide a link against each product to another page where the product details can be edited. I want the link to pass the ID of the product to be edited as a parameter.

I had some difficulty figuring out how to create a HyperLink control with a NavigateURL property that contained the ID so, once I figured it out, I thought I’d write a post for anyone else having difficulty with what must be a fairly common scenario.

At it’s simplest, data binding uses the Eval expression placed between delimiters and looks something like this:

Simple Eval

I used the Northwind database and created a SQLDataSource and a ListView control which I used to embed a table with 2 columns for the Product ID and the Product Name and use the Eval expression to poulate the columns of each row. The code looked like this:

Initial Code

and produced this result:

Results of Initial Code

I wanted to be able to click on the product name to open the page for editing the product details, so I need to replace the product name text

Eval Product Name

with a HyperLink which displayed the product name but linked to a different page and passed the Product ID as a parameter.

First the easy bit. After adding a HyperLink control I took the Eval expression used previously and set the text property equal to it, placing it in single quotes.

Text Property

The more difficult bit was setting the NavigateURL property, which needs to contain the link and the relevant product ID. The format would be NavigateURL=?= resulting in a link such as “Default.aspx?ProductID=22″.

My initial thought was to try to concatenate the “?=” part, which would be constant, with the data binding expression, like this:

First try doesn’t work

However this resulted in the error “If this attribute value is enclosed in quotation marks, the quotation marks must match.”.

I tried replacing “&” with “+” but got the same error message.

Doesn’t work either

After some trial and error I came up with this:

This works

The key difference is that rather than just placing the data binding expression between the delimiters, the whole thing needs to be within the delimiters. The final code looked like this:

The Final Code

That’s it. Hope this is useful to someone!

Written by nakedpm

March 26, 2008 at 11:22 am