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

本文关键字:添加 动态 超链接 视图 网格 何根 特定条件 | 更新日期: 2023-09-27 18:16:55

在我的网站上,我目前使用一个网格视图,它从3个表中生成数据,即状态,Project_glance, Application_header。SQL查询返回4列,但在我的网格视图我只显示3列。最后一列返回项目的Status_id。以下是我的。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>

如果Status_id> 15,那么只有视图超链接将可见,否则视图超链接文本将被更改为"编辑",导航URL将添加到此超链接,另一个超链接"删除"将显示,允许用户删除项目详细信息。

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

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

首先,将delete超链接添加到ItemTemplate中。

然后,能够访问你的Status_id字段,你会想把它添加到你的GridView的DataKeys。

然后,你可以订阅GridView的RowDataBound方法,抓取超链接,检查status_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
 }
}

至于显示"编辑"超链接,我会在"视图"列旁边增加一个额外的列,并根据需要隐藏或显示其他超链接,因为在某些情况下,您需要一个超链接列,在某些情况下,您需要两个。