views:

5486

answers:

8

Hi,

I'm trying to add HyperLinkColumns dynamically to my GridView. I have the following code:

HyperLinkColumn objHC = new HyperLinkColumn();
objHC.DataNavigateUrlField = "title";
objHC.DataTextField = "Link text";
objHC.DataNavigateUrlFormatString = "id, title";
objHC.DataTextFormatString = "{2}";

GridView1.Columns.Add(objHC);

This doesn't work, so.. how can i add a HyperLinkColumn to my GridView?

A: 

It seems you have got things mixed up. I don't know - how that code compiles?

GridView's column collection can accept columns of type "DataControlField". I think you need to initialize HyperLinkField and set relevant properties (text, NavigateUrl, HeaderText, Target) and add it to the columns collection.

HyperLinkColumn class is meaningful when you are using DataGrid (not in case of GridView).

Hope that helps.

shahkalpesh
+1  A: 

You have to do it before the DataBinding takes place, check the GridView Events.

CMS
A: 

@shahkalpesh: Indeed, i mixed things up. It certainly helps. Thnx :)

What makes it negative? :)
shahkalpesh
A: 

You might want to add it when the row is binded:

protected void yourGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
  HyperLink hlControl = new HyperLink();
  hlControl.Text = e.Row.Cells[2].Text; //Take back the text (let say you want it in cell of index 2)
  hlControl.NavigateUrl = "http://www.stackoverflow.com";
  e.Row.Cells[2].Controls.Add(hlControl);//index 2 for the example
}
Daok
A: 

In case, if you just want to redirect to another URL then simple use HyperLink web control and push it in the desired cell of GridView Row at RowDataBound event.
OR
If you want to perform any server event before sending it to another URL, try this
  1) Add LinkButton object at RowDataBound event of GridView.
  2) Set the CommandName, CommandArgument property, if requried to pass any data to this object.
  3) Capture this event by handling the RowCommand event of the GridView.

Sachin Gaur
A: 

By the way, I just think that you can use the DataGridView and in the Designer select the Link column and your problem would be over. The DataGridView does have a link column, than you just need to add an event on "Click" and you will be able to have what you want. This solution works if you can switch to DataGridView.

Daok
A: 

I think you should be using a HyperLinkField not a HyperLinkColumn.

A: 

I know this thread is old but couldn't help adding my 2 cents. The procedure explained in the following tutorial worked perfectly for me: ASP Alliance

mishrsud