DevPinoy.org
A Filipino Developers Community
   
How To: Use a HyperLink control inside a GridView

I decided to create this demo after seeing a post on devpinoy.org today that is asking about how to pass a value from a gridview to another page using HyperLinks. I decided to extend it a little bit so that we could show alittle bit more functionality.

Lets start:

First we need to setup our grid in our main page called RedirectMyGridView.aspx:

<asp:GridView ID="urlGrid" runat="server" AutoGenerateColumns="False">
   <Columns>
      <asp:TemplateField>
         <ItemTemplate>
            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"SiteId","RedirectToUrl.aspx?SiteId={0}" ) %>'
            Text="Go!"></asp:HyperLink>
         </ItemTemplate>
      </asp:TemplateField>
      <asp:BoundField DataField="SiteName" HeaderText="Site Name" />
   </Columns>
</asp:GridView>

Next we need to create our datasource and bind it on our page_load event:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class RedirectMyGridView : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      if (!IsPostBack)
      {
         this.BuildGridViewItems();
      }
   }

   private void BuildGridViewItems()
   {
      DataTable dt = new DataTable();

      DataColumn siteIdColumn = new DataColumn("SiteId");
      DataColumn siteNameColumn = new DataColumn("SiteName");

      dt.Columns.Add(siteIdColumn);
      dt.Columns.Add(siteNameColumn);

      DataRow dr1 = dt.NewRow();
      dr1[siteIdColumn] = "1";
      dr1[siteNameColumn] = "Google";
      dt.Rows.Add(dr1);

      DataRow dr2 = dt.NewRow();
      dr2[siteIdColumn] = "2";
      dr2[siteNameColumn] = "Yahoo";
      dt.Rows.Add(dr2);

      DataRow dr3 = dt.NewRow();
      dr3[siteIdColumn] = "3";
      dr3[siteNameColumn] = "MSN";
      dt.Rows.Add(dr3);
      
      DataRow dr4 = dt.NewRow();
      dr4[siteIdColumn] = "4";
      dr4[siteNameColumn] = "DevPinoy";
      dt.Rows.Add(dr4);

      urlGrid.DataSource = dt;
      urlGrid.DataBind();
   }
}

After that we need to setup our accepting page called RedirectToUrl.aspx:

using System;

public partial class RedirectToUrl : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      if (Request.QueryString["SiteId"] != null)
      {
         string redirectionUrl = "";
         try
         {
            //get the value of the site id;
            int siteId = int.Parse(Request.QueryString["SiteId"].ToString());
            //check if siteid is inside the defined bounds. do nothing if it fails.
            if (siteId > 4 || siteId < 1) { return; }
            //chck and compare
            if (siteId == 1) { redirectionUrl = "http://www.google.com"; }
            else if (siteId == 2) { redirectionUrl = "http://www.yahoo.com"; }
            else if (siteId == 3) { redirectionUrl = "http://www.msn.com"; }
            else if (siteId == 4) { redirectionUrl = "http://www.devpinoy.com"; }
            //redirect to the selected location
            Response.Redirect(redirectionUrl);
         }
         catch
         {
            //throw our error.
            throw new Exception("cannot parse siteid... value must be out of range!");
         }
      }
   }
}

So what happens when we run this? The data would be binded to our datagrid on the page_load event of RedirectMyGridView.aspx. The controls would be populated with the corresponding values that we have specified on the itemtemplate of our GridView. Also note that we have formatted our hyperlink to point to our target url which is RedirectToUrl.aspx so that it would redirect to our target url when click. Our child page then has some pre-filters on it's page load to check and see if the value passed on the siteid query string variable is valid value and then redirects it to the specific url for that id.


Posted 09-10-2006 6:13 PM by keithrull

Comments

CryptoKnight wrote re: How To: Use a HyperLink control inside a GridView
on 09-10-2006 7:10 PM

Hi Keith,

You can also do this... (w/c I prefer) ;-)

<asp:HyperLink ID="HyperLink1" DataNavigateUrlFields="SiteId" DataNavigateUrlFormatString="RedirectToUrl.aspx?SiteId={0}" />

Regards!

keithrull wrote re: How To: Use a HyperLink control inside a GridView
on 09-10-2006 9:25 PM

true! i forgot about this one :D your approach is a better and clearer way... thanks crypto!

CryptoKnight wrote re: How To: Use a HyperLink control inside a GridView
on 09-10-2006 9:57 PM

my pleasure, keith... it should be a HyperLinkField ;-) (replace the whole <asp:TemplateField>)...

<asp:HyperLinkField DataTextField="SiteName" HeaderText="Site Name" DataNavigateUrlFields="SiteID" DataNavigateUrlFormatString="RedirectToUrl.aspx?SiteId={0}" />

Happy Coding!

keithrull wrote re: How To: Use a HyperLink control inside a GridView
on 09-11-2006 12:36 AM

yup! mine was inside a template column.

i guess i should stop using datalist and repeaters.. cause its making me use their object approach even on a GridView :D

l30 wrote re: How To: Use a HyperLink control inside a GridView
on 09-19-2006 8:54 PM

hehe dami ko natutunan dito ahh..

thanks =)

ssp wrote re: How To: Use a HyperLink control inside a GridView
on 02-01-2007 11:37 PM

I am displaying a db content using

<%# DataBinder.Eval(Container.DataItem, "Description") %>

& it contains a description with url/s in it. Now while displaying in browser, I wish to make the url/s act directly clickable or as a hyperlink/s..

how do we perform this.

Sorry bit new to using asp.net

Ricardo Lowe (devpinoy@ricardolowe.emailfish.net) wrote re: How To: Use a HyperLink control inside a GridView
on 02-15-2007 10:46 AM

What if I wanted to bind the value of a control outside of the gridview datasource to the hyperlink.

Something like:

<asp:Label id="lblYear" Text="2007" />

<asp:gridview ...

....

..      <asp:hyperlinkfield  ID="HyperLink1" DataNavigateUrlFields="SiteId" DataNavigateUrlFormatString="RedirectToUrl.aspx?SiteId={0}&YEAR=<%=lblYear.Text%>"  />

</asp:gridview>

How would I do that???

keithrull wrote re: How To: Use a HyperLink control inside a GridView
on 02-15-2007 3:41 PM

try this <%# lblYear.Text  %>

<%= is the same as response.write but since this is a binding event you need to use <%# instead.

gotcha wrote re: How To: Use a HyperLink control inside a GridView
on 07-24-2007 9:54 AM

i'm using the hyperlink control to point to documents uploaded on another server whose link i'm providing thro code-behind using ".NavigateUrl" My issue is that when i try to view these url's ...everytime i get http 500 internal server error only at the first time.if you refresh the page you can view the url correctly.

any help appreciated!!

nomeanas wrote re: How To: Use a HyperLink control inside a GridView
on 10-14-2008 11:48 AM

cool

Copyright DevPinoy 2005-2008