C# 如何根据一定条件在网格视图中添加动态超链接

C# 如何根据一定条件在网格视图中添加动态超链接,c#,asp.net,gridview,C#,Asp.net,Gridview,在我的网站中,我目前使用的是一个网格视图,它从三个表生成数据,即状态、项目、应用程序标题。SQL查询返回4列,但在我的网格视图中,我只显示3列。最后一列返回项目的状态\ id。以下是my.aspx代码: <asp:GridView ID="grdProf" runat="server" AllowPaging="True" AutoGenerateColumns="false" OnPageIndexChanging="grdProf_PageIndexChanging"> &l

在我的网站中,我目前使用的是一个网格视图,它从三个表生成数据,即状态、项目、应用程序标题。SQL查询返回4列,但在我的网格视图中,我只显示3列。最后一列返回项目的状态\ id。以下是my.aspx代码:

<asp:GridView ID="grdProf" runat="server" AllowPaging="True"   AutoGenerateColumns="false" OnPageIndexChanging="grdProf_PageIndexChanging">
<Columns>
  <asp:TemplateField>
        <ItemTemplate>
           <asp:HyperLink ID="hlnkView" Visible="true" Text="View" runat="server" >     </asp:HyperLink>
        </ItemTemplate>
  </asp:TemplateField>
  <asp:BoundField DataField="ApplicationID" HeaderText="ApplicantionID" />
  <asp:BoundField DataField="PRGLProjectTitle" HeaderText="Project Title" />
  <asp:BoundField DataField="Status" HeaderText="Project Status" />
</Columns>
</asp:GridView>

如果状态_id>15,则只有视图超链接可见,否则视图超链接文本将更改为“编辑”,导航URL将添加到此超链接,并显示另一个超链接“删除”,以允许用户删除项目详细信息


请帮助我找到正确的解决方案。

首先,将删除超链接添加到您的ItemTemplate

然后,为了能够访问Status_id字段,您需要将其添加到GridView的数据键中

然后,您可以订阅GridView的RowDataBound方法,获取超链接,检查状态id,并相应地设置超链接的可见性

<asp:GridView DataKeyNames="status_id"

<ItemTemplate>
     <asp:HyperLink ID="hlnkView" Visible="true" Text="View" runat="server" >
     <asp:HyperLink ID="hlnkDelete" Visible="false" Text="Delete" runat="server" >
</asp:HyperLink>

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
    HyperLink delHl = e.Row.Cells[0].FindControl("hlnkDelete") as HyperLink;
    int statusId = (int)(sender as GridView).DataKeys[e.Row.RowIndex].Value;
    delHl.Visible = statusId <= 15; 
}
像这样

protected void grdProf_RowDataBound(Object sender, GridViewRowEventArgs e)
{

 if(e.Row.RowType == DataControlRowType.DataRow)
 {

   DataRowView rowView = (DataRowView)e.Row.DataItem;

   // Retrieve the status value for the current row. 
   string status = rowView["Status"].ToString();
   //Now you have the status 
   //get a reference to view hyperlink and hide it if that's the case
   Hyperlink hlnkView = e.Row.FindControl("hlnkView") as HyperLink;
   //example: 
   if(int.Parse(status)>15)
      hlnkView .Visible=false;//you are done

 }
}

至于显示“编辑”超链接,我会在“查看”列旁边增加一列,并根据需要隐藏或显示另一个超链接,因为在某些情况下,您需要一个超链接列,在某些情况下,您需要两个超链接列。

它显示这一行的索引超出范围错误
int statusid=(int)(发件人作为GridView).DataKeys[e.Row.RowIndex]。值
。那我该怎么办?@Nupur您是否在GridView定义中添加了
DataKeyNames=“status\u id”
?是的,我在GridView定义中添加了DataKeyNames=“status\u id”。是的,我在GridView定义中添加了DataKeyNames=“status\u id”。它显示了以下错误“指数超出范围。必须为非负数且小于集合的大小。参数名称:INDExpress请不要在多个站点上发布相同的问题。这已迁移,现在需要合并。所有这些都为社区的其他成员和版主工作。