DarkW1nter
DarkW1nter

Reputation: 2851

hyperlink in gridview

I have a hyperlink in a gridview which I want users to click on and it directs them to a particular page and also either passes in the first field of the gridview (the ID) or holds it in session, preferebly in session.

The link is just static text so no matter what record they click on i want to get them to the same page, but with that records ID available.

Just not sure how to add this to the NavigateUrl of the hyperlink.

ANy hints appreciated, thanks

Upvotes: 0

Views: 1472

Answers (4)

PhilPursglove
PhilPursglove

Reputation: 12589

You can easily generate the URL in the markup of your GridView without resorting to code. What you need to do is:

  1. In the DataNavigateUrlFields property of your HyperLinkField, put the name of the column that contains your id.
  2. In the DataNavigateUrlFormatString, put the path to your page, plus the querystring that the next page will use to get the id, but where the value should go, put {0} instead.

e.g.

<asp:Hyperlink DataNavigateUrlFields="ProductId" DataNavigateUrlFormatString="details.aspx?id={0} />

When the control is rendered at runtime, you will find that for each row, the {0} is replaced by the value of the ProductId column.

See String.Format and DataNavigateUrlFormatString for more details.

Upvotes: 1

ankur
ankur

Reputation: 4733

Not sure why you have taken server control instead of tag of HTML.

two ways you can do it.

1)if it is an static link just prefix the page name and append the id in mark up. for ex

<a  href='myPage.aspx<%#Eval("YourID")%>'><strong>Click me to navigate</strong></a>

2)give some id to the a tag and make it runat server handle the data bound event and bind the value to it.

 protected void MyGridview_ItemDataBound(object sender, ListViewItemEventArgs e)
    {


 HtmlAnchor AncImage = e.Item.FindControl("AncImage") as HtmlAnchor;
AncImage.href="myPage.aspx"/id=" + DataBinder.Eval(e.Row.DataItem, "ID"); ;
//the id is the value that you want to append for redirection
}

Upvotes: 0

Arief
Arief

Reputation: 6085

Use HyperLink control and then write an event handler function for RowDataBound event, like this:

protected void OnRowDataBound(object source, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink hyperLink = e.Row.FindControl("hyperLinkID") as HyperLink;

        // example, adjust this to your needs.
        hyperLink.NavigateUrl = "~/detail.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "ID");     
    }
}

Upvotes: 0

VMAtm
VMAtm

Reputation: 28355

  1. You can handle the Row_DataBound event to find the hyperlink control and update the NavigateUrl property.
  2. You can add simple html control Text to link, it will produce same html.

Upvotes: 0

Related Questions