如何在Gridview的RowCommand事件中指定超链接itemtemplate的Navigate url

时间:2014-10-13 06:44:48

标签: c# asp.net gridview

在我的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;
    }
}

2 个答案:

答案 0 :(得分:0)

我认为您不需要 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";
    }
}

现在您需要在模板字段中使用 HyperLink 控件,而不是 HyperLinkField

答案 1 :(得分:0)

在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>