C# 如何在asp.net的gridview中创建链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19798685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create a link in gridview in asp.net
提问by Arif YILMAZ
I am trying to create a webpage that has a gridview. this gridview is supposed to have a link like below
我正在尝试创建一个具有 gridview 的网页。这个gridview应该有一个像下面这样的链接
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.
当用户单击 gridview 中的行链接之一时,它将打开一个空白页面并显示一些结果。
here is how I bind data to the gridview but I dont know how to set the link
这是我如何将数据绑定到 gridview 但我不知道如何设置链接
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?
如何从 CODE 列中创建链接?
采纳答案by Smeegs
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
这有一个技巧。Hyperlinkcolumn 将不起作用,因为您无法格式化链接。您想使用边界字段并格式化文本。像这样
<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.
或者,如果您需要指定编辑和插入模板,您可以使用模板字段。
回答by Tim
You should be able to use a HyperLinkColumn in your markup.
您应该能够在标记中使用 HyperLinkColumn。
回答by Karl Anderson
Add this to your Columns
definition in the markup for your grid view:
将此添加到您Columns
的网格视图标记中的定义中:
<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>
回答by Hyman.the.ripper
to 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>