Wednesday, January 02, 2008

How to Add a URL column for a GridView in ASP.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim ds As DataSet = New DBClass().SelectQueryforData()
Me.AddGrid(ds.Tables(0))
End Sub
Private Sub AddGrid(ByVal t As DataTable)
For Each c As DataColumn In t.Columns
If c.ColumnName = "PK_ID_Column" Then
Dim y As HyperLinkField
y = New HyperLinkField()
y.DataTextField = c.ColumnName
y.HeaderText = c.ColumnName
y.DataNavigateUrlFormatString = "~/YourUrl.aspx?q={0}"
y.DataNavigateUrlFields = New String() {c.ColumnName}
Me.GridView1.Columns.Add(y)
Else
Dim x As BoundField
x = New BoundField()
x.DataField = c.ColumnName
x.HeaderText = c.ColumnName
Me.GridView1.Columns.Add(x)
End If
Next
Me.GridView1.AutoGenerateColumns = False
Me.GridView1.DataSource = t
Me.GridView1.AlternatingRowStyle.BackColor = Drawing.Color.AliceBlue
Me.GridView1.DataBind()
End Sub

Enjoy IT!