c# - 在网格视图中显示静态超链接
问题描述
我正在从列名 Nature 中获取 SQL DB 中的数据,应根据 Nature 的值确定超链接。
如果大自然的价值是
- A 或 B 或 C :链接应为“ http://www.this.is.test1 ”
- X 或 Y 或 Z :链接应为“ http://www.this.is.test2 ”
- P 或 Q 或 R :链接应为“ http://www.this.is.test3 ”
页面上的输出应该是:
自然链接(页面上的列名)
如果值为 A -----> A(单击“A”链接http://www.this.is.test1应打开)
如果值为 Q -----> Q(点击“Q”链接http://www.this.is.test3应该打开)
我无法为此显示值(A、B、C、P、Q....)和相关链接。
试过了
1.在Gridview中使用HyperlinkField
<asp:HyperlinkField HeaderText="Nature Link" DataTextField="Nature"
Visible="true" SortExpression="Nature"
DataNavigateUrlFormatString="http://www.this.is.{0}"
DataNavigateUrlFields="Nature" target="_blank"></asp:HyperlinkField>
代码 :
protected void dginvoicereport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
var t_nature= Int32.Parse(e.Row.Cells[25].Text.Replace(" ",""));
if ((t_nature== 'A') || (t_nature== 'B') || (t_nature== 'C'))
e.Row.Cells[25].Text = "test1";
else if ((t_nature== 'X') || (t_nature== 'Y') || (t_nature== 'Z'))
e.Row.Cells[25].Text = "test2";
}
}
2. 这个:
<asp:BoundField DataField="nature" HeaderText="Nature Link"
HtmlEncode="False" DataFormatString="<a target='_blank'
href='http://www.this.is.{0}'>Link</a>" /> `
解决方案
在后面的代码中创建方法以检查 Nature 的值并返回所需的链接,如下所示
protected string GeNatureLink(string nature)
{
string naturetLink = "http://www.this.is.test1";
switch (nature)
{
case "A": case "B": case "C":
break;
case "X": case "Y": case "Z":
naturetLink = "http://www.this.is.test2";
break;
case "P": case "Q": case "R":
naturetLink = "http://www.this.is.test3";
break;
default:
break;
}
return naturetLink;
}
在GridView
下面添加TemplateField
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink Target="_blank" ID="hyperlink" NavigateUrl='<%# GeNatureLink(Eval("Title") as string) %>' Text='<%# Eval("Title") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>