Friday, October 21, 2011

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 ofRedirectMyGridView.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 isRedirectToUrl.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.