如何在Gridview的RowCommand事件中指定超链接项模板的导航url
本文关键字:超链接 url 导航 Gridview RowCommand 事件 | 更新日期: 2023-09-27 18:26:16
在我的Gridview
中,我有一个超链接作为itemtemplate(非链接按钮)。我想在gridview的行命令事件中指定它的导航url。因为每个超链接都会重定向到不同的pdf文件。
这怎么可能?我试过这样做,但超链接的导航链接没有出现。
<asp:TemplateField ShowHeader="true" HeaderText="Certificates" HeaderStyle-BackColor="#98272d" ItemStyle-HorizontalAlign="Center">
<ItemTemplate >
<asp:HyperLink ID="lb_certificate" runat="server" ForeColor="Black"
CommandName="cc" CommandArgument='<%#Eval("student_id")%>'>Certificate</asp:HyperLink >
</ItemTemplate>
</asp:TemplateField >
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string st_id = Convert.ToString(e.CommandArgument.ToString());
if (e.CommandName == "cc")
{
GridViewRow row = (GridViewRow)(((HyperLink)e.CommandSource).NamingContainer);
HyperLink lnkbtn = (HyperLink)row.FindControl("lb_certificate");
string ss = st_id + "Cc.pdf";
string year="2014";
string path = Server.MapPath("~/results/certificates/" + st_id + "/" + year + "/");
lnkbtn.NavigateUrl = path + s_certificate;
}
}
我认为您不需要RowCommand,甚至不需要
TemplateField这里,您只需使用
HyperLinkField即可实现,如:
<asp:HyperLinkField Text="Certificate" DataNavigateUrlFields="student_id"
DataNavigateUrlFormatString="~/results/certificates/{0}/{0}Cc.pdf" />
编辑:对于包含年份,如果它将保持不变,则可以使用。
<asp:HyperLinkField Text="Certificate" DataNavigateUrlFields="student_id"
DataNavigateUrlFormatString="~/results/certificates/{0}/2014/{0}Cc.pdf" />
如果它是动态的,那么您应该使用类似的RowDataBound事件
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink lnkbtn = (HyperLink)e.Row.FindControl("lb_certificate");
int year = DateTime.Now.Year; //Or your Variable where year is stored.
// If you are binding with Collection of Object, you can use this
//var data = (ObjectClass)e.Row.DataItem;
//lnkbtn.NavigateUrl = "~/results/certificates/" + data.student_id + "/" + year + "/" + data.student_id + "Cc.pdf";
//If you are binding with DataTable
var data = (DataRowView)e.Row.DataItem;
lnkbtn.NavigateUrl = "~/results/certificates/" + data["student_id"] + "/" + year + "/" + data["student_id"] + "Cc.pdf";
}
}
现在您需要在templatefield中使用HyperLink控件,而不是在HyperLinkField上使用。
在gridview 中绑定超链接
<asp:HyperLink ID="lb_certificate" runat="server" ForeColor="Black" CommandName="cc"
NavigateUrl='<%#"~/results/certificates/"+Eval("student_id")+"Cc.pdf" %>' CommandArgument='<%#Eval("student_id")%>'>Certificate</asp:HyperLink>