Martijn
Martijn

Reputation:

C# Add HyperLinkColumn to GridView

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?

Upvotes: 1

Views: 29144

Answers (7)

Sudhanshu Mishra
Sudhanshu Mishra

Reputation: 6733

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

Upvotes: 0

Dan Anos
Dan Anos

Reputation:

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

Upvotes: 1

Patrick Desjardins
Patrick Desjardins

Reputation: 140893

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.

Upvotes: 0

Sachin Gaur
Sachin Gaur

Reputation: 13099

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.

Upvotes: 0

Patrick Desjardins
Patrick Desjardins

Reputation: 140893

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
}

Upvotes: 5

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827606

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

Upvotes: 1

shahkalpesh
shahkalpesh

Reputation: 33474

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.

Upvotes: -2

Related Questions