Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Navigation url to hyperlink dynamically

Tags:

c#

asp.net

Im trying to set navigation url to a hyperlink which is inside a gridview.

Im creating the table inside the gridview using a literal in backend c# code.

The code now look like inside GridviewRowDataBound(object sender, GridViewRowEventArgs e)

Literal.Text += "<asp:HyperLink ID='hlContact' runat='server' NavigateUrl='#'>Contact </asp:HyperLink>";

I want to set the navidation inside this code

If anyone have an idea it will be helpful

Thanks

like image 521
huMpty duMpty Avatar asked Feb 23 '23 00:02

huMpty duMpty


2 Answers

You should just create a HyperLink control, instead of trying to add one to a literal:

HyperLink lnk = new HyperLink();
lnk.Text = "Hello World!";
lnk.NavigateUrl = "~/somefolder/somepage.aspx";

e.Row.Cells[0].Controls.Add(lnk);

If your approach can work, you could try something like this:

Literal.Text += String.Format("<asp:HyperLink ID=\"hlContact\" runat=\"server\" NavigateUrl=\"{0}\">Contact</asp:HyperLink>", navigationUrl); 

If you want to use a Literal control though, I would do something like this instead:

Literal.Text += String.Format("<a href=\"{0}\">Contact</a>", navigationUrl); 
like image 196
James Johnson Avatar answered Mar 04 '23 13:03

James Johnson


If you are just trying to simply databind a HyperLink field in a GridView with a bound field, you can use a TemplateField. Here is an example to do it up front and not the hassle of adding it in the code behind.

<asp:TemplateField HeaderText="Contact" SortExpression="LastName, FirstName">
    <ItemTemplate>
        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# String.Format("~/Page.aspx?ID={0}", Eval("CustID").ToString()) %>'>Contact</asp:HyperLink>)
    </ItemTemplate>
</asp:TemplateField>
like image 37
Kirk Avatar answered Mar 04 '23 13:03

Kirk