C # Add HyperLinkColumn to GridView

I am 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);

      

It doesn't work, so .. how can I add the HyperLinkColumn to my GridView?

+1


source to share


7 replies


You can add it when the string is anchored:



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
}

      

+5


source


You must do this before the DataBinding happens, check the GridView Events .



+1


source


I think you should be using HyperLinkField and not HyperLinkColumn.

+1


source


In case you just want to redirect to a different url, just use the HyperLink web control and push it into the desired cell of the GridView Row in the RowDataBound event.
OR
If you want to execute some server event before sending it to another url try this
  1) Add LinkButton object to RowDataBound event in GridView.
  2) Set the CommandName property, CommandArgument if it is required to pass any data to this object.
  3) Catch this event by handling the RowCommand event in the GridView.

0


source


BTW, I just think you can use the DataGridView and in the Designer select the "Link" column and your problem is over. The DataGridView has a column of links than you just need to add an event on "Click" and you can have what you want. This solution works if you can switch to DataGridView.

0


source


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

0


source


It seems that you are all confused. I don't know how this code compiles?

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

The HyperLinkColumn class makes sense when you are using a DataGrid (not in the case of a GridView).

Hope it helps.

-2


source







All Articles