In this article I will explain how to make use of HyperLinkField to create HyperLink columns in ASP.Net GridView.
HTML Markup
The HTML Markup consists of ASP.Net GridView control with HyperLinkField and BoundField columns
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:HyperLinkField DataTextField="Name" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="~/Details.aspx?Id={0}"
HeaderText="Name" ItemStyle-Width = "150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width = "150" />
</Columns>
</asp:GridView>
HyperLinkField Column
The HyperLinkField column consists of the following properties that are mainly useful for binding data
DataTextField – Here we set the name of the field or column that we need to display.
DataNavigateUrlFields – Here we set the name of the field or column that we need to pass via QueryString parameter in URL.
DataNavigateUrlFormatString – Here we set the URL of the page along with the QueryString Parameter and also provide a place holder {0} that will be replaced by the actual value of the column that we have set in the DataNavigateUrlFields field at runtime.
Binding the GridView
I have made use of DataTable with some dummy values for this article.
Namespaces
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Demo
Downloads