Adding HyperLink Column to GridView dynamically

This article is written by Pon Saravanan  on 26-Aug-09 Last modified on :13-Sep-09

Subscribe to my RSS Feed!

Adding HyperLink column to GridView at runtime dynamically

Even there are various ways to add HyperLink to GridView, the following way I am going to explain is very clean and reusable. However may not simple if it is used in only one place. While considering its reusablity. It actually reduces a lot of duplication inside the code.

Adding HyperLink Column at design time to the GridView

While adding HyperLink column at design time is easier and you can attach attributes to the HyperLink directly at markup. There are times HyperLink has to be created at runtime. If this is the case then this article is written focused on that. However the following is the sample of “Adding HyperLink Column at design time

<asp:TemplateField >
<ItemTemplate>
add Hyperlink here
</ItemTemplate>
</asp:TemplateField>

Adding HyperLink Column at runtime dynamically to the GridView

While adding HyperLink column at runtime, we need to consider following the same hierarchy as the TemplateField. So we must create a TemplateField.  Add respective templates such as ItemTemplate, EditItemTemplate, and HeaderTemplate. In our case we are trying only ItemTemplate for making article simpler. And adding these objects should happen at Form.Init Event.

HyperLinkColumn is the main class we have to deal for loading hyperlinks at runtime. This class is responsible for creating and data binding the HyperLink in the column.

HyperLinkTemplate: The Custom Template for HyperLink

This HyperLinkTemplate gets ColumnName as input for fetching the data. This can be either by constructor’s parameter or as a property.  This class must implement ITemplate to behave as a custom template. If the ITemplate is implemented it has to implement InstantiateIn method.

How to pass values to QueryString

To pass values to QueryString  Names and Values has to be passed along with ? &. However in the HyperLink column the values usualy have to come from the database. So i have made it as two properties named QueryStringNames, and QueryStringValues. Both should be comma seperated. If QueryStringNames has 3 comma seperated items, then QueryStringValues also should have 3 comma seperated items. And first item in QueryStringNames related to first item in QueryStringValues the rest goes on like this.  Refer the source code for better understandings.

MyLink.QueryStringNames = "id,name" 'name of the querystring items
MyLink.QueryStringValues = "ProductId,ProductName" 'name of the querystring values from dataitem
here id is the name of the querystring parameter, ther respective column from db suppose to be ProductId.

InstantiateIn from ITemplate

This is the function actually the HyperLink gets created in. After the creation the control has to be bound to the data. DataBinding event has to be handled for filling up the data. The data can be fetched from the GridViewRow’s DataItem Object.

Source Code


MarkUp(.Aspx)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="ProductID" />
        
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>


CodeBehind(.Aspx.Vb)

Imports System.Data.SqlClient
Imports System.Data
Imports Microsoft.VisualBasic
Partial Class _Default
    Inherits System.Web.UI.Page
    Private ReadOnly Property ConnectionString() As String
        Get
            Return "Server=.\SQLEXPRESS;Database=NorthWind;Trusted_Connection=True"
        End Get
    End Property
    Private ReadOnly Property Connection() As SqlConnection
        Get
            Dim ConnectionToFetch As New SqlConnection(ConnectionString)
            ConnectionToFetch.Open()
            Return ConnectionToFetch
        End Get
    End Property
    Public Function GetData() As DataTable
        Dim SelectQry = "select * from Products"
        Dim SampleSource As New DataSet
        Try
            Dim SampleDataAdapter As New SqlDataAdapter(SelectQry, ConnectionString)
            SampleDataAdapter.Fill(SampleSource)
        Catch ex As Exception
            Throw ex
        End Try
        Return SampleSource.Tables(0)
    End Function
    Protected Sub form1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Init
        CreateHyperLinkColumn()
    End Sub
    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If (Not IsPostBack) Then
            Response.Write("<br>ID : " & Request.QueryString("Id"))
            Response.Write("<br>Name : " & Request.QueryString("name"))
            LoadGrid()

        End If
    End Sub
    Private Sub LoadGrid()
        GridView1.DataSource = GetData()
        GridView1.DataBind()
    End Sub
    Private Sub CreateHyperLinkColumn()
        Dim TemplatedColumn As New TemplateField()
        Dim MyLink As New HyperLinkTemplate("ProductName")
        MyLink.NavigateTo = Me.Request.Url.AbsolutePath 'specify your page/path here
        MyLink.QueryStringNames = "id,name" 'name of the querystring items
        MyLink.QueryStringValues = "ProductId,ProductName" 'name of the querystring values from dataitem
        TemplatedColumn.ItemTemplate = MyLink
        GridView1.Columns.Add(TemplatedColumn)
    End Sub
End Class

Template Class(.VB)

Public Class HyperLinkTemplate
    Implements ITemplate
    Private m_ColumnName As String
    Public Property ColumnName() As String
        Get
            Return m_ColumnName
        End Get
        Set(ByVal value As String)
            m_ColumnName = value
        End Set
    End Property
    Private m_NavigateTo As String
    Public Property NavigateTo() As String
        Get
            Return m_NavigateTo
        End Get
        Set(ByVal value As String)
            m_NavigateTo = value
        End Set
    End Property
    Private m_QueryStringNames As String
    Public Property QueryStringNames() As String
        Get
            Return m_QueryStringNames
        End Get
        Set(ByVal value As String)
            m_QueryStringNames = value
        End Set
    End Property
    Private m_QueryStringValues As String
    Public Property QueryStringValues() As String
        Get
            Return m_QueryStringValues
        End Get
        Set(ByVal value As String)
            m_QueryStringValues = value
        End Set
    End Property
    Public Sub New()
    End Sub
    Public Sub New(ByVal ColumnName As String)
        Me.ColumnName = ColumnName
    End Sub
    Private Sub InstantiateIn(ByVal ThisColumn As System.Web.UI.Control) Implements ITemplate.InstantiateIn
        Dim HyperLinkItem As New HyperLink()
        HyperLinkItem.ID = "hl" & ColumnName
        AddHandler HyperLinkItem.DataBinding, AddressOf HyperLinkItem_DataBinding
        ThisColumn.Controls.Add(HyperLinkItem)
    End Sub
    Private Sub HyperLinkItem_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
        Dim HyperLinkItem As HyperLink = DirectCast(sender, HyperLink)
        Dim CurrentRow As GridViewRow = DirectCast(HyperLinkItem.NamingContainer, GridViewRow)
        Dim CurrentDataItem As Object = DataBinder.Eval(CurrentRow.DataItem, ColumnName)
        If Not CurrentDataItem Is DBNull.Value Then
            HyperLinkItem.Text = CurrentDataItem.ToString()
            Dim NavigateUrl = NavigateTo
            If (Not String.IsNullOrEmpty(QueryStringNames) AndAlso _
                Not String.IsNullOrEmpty(QueryStringValues)) Then
                Dim ItemIndex = 0
                For Each ItemName In QueryStringNames.Split(",")
                    If (NavigateUrl.Contains("?")) Then
                        NavigateUrl &= "&"
                    Else
                        NavigateUrl &= "?"
                    End If
                    Dim QueryDataItem = DataBinder.Eval(CurrentRow.DataItem, QueryStringValues.Split(",")(ItemIndex))
                    NavigateUrl &= ItemName & "=" & QueryDataItem.ToString()
                    ItemIndex += 1
                Next
            End If
            HyperLinkItem.NavigateUrl = NavigateUrl
        End If
    End Sub
End Class









GUEST
Excellentttttt 11/27/2009 5:54:08 PM

GUEST
test 2/3/2010 10:08:31 PM


Comments
   
Captcha Image
For you specially:  
Captcha Text Enter the text in the image.(Not Case sensitive)    




Spam Bot Trap