How to create a link in gridview in asp.net

I am trying to create a webpage with gridview. this gridview is supposed to have a link as below

http://localhost/Test.aspx?code=123 

when the user clicks on one of the rows in the gridview, he opens a blank page and displays some result.

this is how i bind data to gridview but i don't know how to set link

 protected void Page_Load(object sender, EventArgs e) { string firma_no = logoFrmNr.ToString().PadLeft(3, '0'); string active_period = logoFrmPeriod.PadLeft(2, '0'); SqlConnection conn = new SqlConnection(conStr); string selectSql = @"SELECT LOGICALREF, CODE , DEFINITION_ , FROM LG_CLFLINE"; SqlCommand cmd = new SqlCommand(selectSql, conn); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); conn.Close(); } 

here is the markup

 <asp:GridView ID="GridView1" runat="server" EnableModelValidation="True"> </asp:GridView> 

How can I make a link from a CODE column?

+7
c # gridview linkbutton
source share
4 answers

There is a trick. The hyperlink will not work because you cannot format the link. You want to use the linked field and format the text. Thus

 <asp:GridView ID="GridView1" runat="server" EnableModelValidation="True"> <Columns> <asp:BoundField DataField="Code" HtmlEncode="False" DataFormatString="<a target='_blank' href='Test.aspx?code={0}'>Link Text Goes here</a>" /> </Columns> </asp:GridView> 

Alternatively, you can use the template field if you need to assign editing and insert templates.

+6
source share

Add this to the Columns definition in the markup for your grid view:

 <asp:TemplateField HeaderText="Hyperlink"> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("CODE", @"http://localhost/Test.aspx?code={0}") %>' Text='link to code'> </asp:HyperLink> </ItemTemplate> </asp:TemplateField> 
+7
source share

for me it would be something like

 <asp:DataGrid id="MyDataGrid" GridLines="Both" AutoGenerateColumns="false" runat="server"> <HeaderStyle BackColor="#aaaadd"/> <Columns> <asp:HyperLinkColumn HeaderText="Select an Item" DataNavigateUrlField="code" DataNavigateUrlFormatString="http://localhost/Test.aspx?code={0}" Target="_blank"/> </Columns> </asp:DataGrid> 
+3
source share

In your markup, you should use HyperLinkColumn.

HyperlinkColumn Documentation

+2
source share

All Articles