I am trying to create a webpage that has a gridview. this gridview is supposed to have a link like below
http://localhost/Test.aspx?code=123
when the user clicks one of the rows' link in gridview, it will open a blank page and display some result.
here is how I bind data to the gridview but I dont know how to set the 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 out of CODE column?
Hover your mouse over the GridView and click the arrow that appears in the top right. Go to "Choose Data Source" and select "new data source..." Create the connection string to your database and choose the NewsHeadline table.
There's a trick to this. The Hyperlinkcolumn won't work, because you can't format the link. You want to use a boundfield and format the text. Like so
<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>
Alternately, you can use a templatefield if you need to designate edit and insert templates.
Add this to your 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With