Malik
Malik

Reputation: 347

Adding a hyperlink column to a 'GridView' dynamically (server-side)

I have an ASP.NET application that reads an XML source and creates columns in a GridView. This same XML source is used to create columns in a DataTable. The application populates the DataTable and then binds the DataTable to the GridView using server-side code.

Now I want to display a hyperlink in the GridView and am not sure how to do it. (Note that the application is not making use of the RowDataBound event.)

Here is what I have thus far:

foreach (XmlNode columnNode in columnNodes)
{    
    dc = new DataColumn(columnNode.Attributes["ColumnName"].Value,
        Type.GetType("System.String"));
    dt.Columns.Add(dc);

    boundField = new BoundField();
    boundField.HeaderText = columnNode.Attributes["ColumnDisplayName"].Value;
    boundField.DataField = columnNode.Attributes["ColumnName"].Value;
    boundField.SortExpression = columnNode.Attributes["ColumnName"].Value; 
    grdView.Columns.Add(boundField);    
} 

where dt is a DataTable and grdView is a GridView.

Upvotes: 2

Views: 9272

Answers (1)

Josh Darnell
Josh Darnell

Reputation: 11433

You should use a HyperLinkField to accomplish this; it's a type of bound field specifically designed for displaying and formatting hyperlinks. You only need to slightly update your code:

linkField = new HyperLinkField();
linkField.HeaderText = columnNode.Attributes["ColumnDisplayName"].Value;
// The field you want to use as the displayed text of the hyperlink
linkField.DataTextField = columnNode.Attributes["ColumnName"].Value;
// The field(s) you want to use in the URL behind the hyperlink
linkField.DataNavigateUrlFields = new string[] { columnNode.Attributes["ColumnName"].Value };
// The formatting string for your hyperlink.  Use this to build the links the way you want them.
linkField.DataNavigateUrlFormatString = "http://yourSiteName/links/{0}";
linkField.SortExpression = columnNode.Attributes["ColumnName"].Value; 
grdView.Columns.Add(linkField);

The part you've left out of your question is what you want these hyperlink URLs to look like. The DataNavigateUrlFormatString is pretty flexible (it works like String.Format, so you can construct a URL from static text and embedding text from your datafields).

Upvotes: 2

Related Questions