HyperLink到gridview行中的特定项目

时间:2014-04-17 22:13:41

标签: c# asp.net gridview hyperlink

所以我正在一个篮球网站上工作。有一个充满团队的网格视图,当我点击一个团队名称时,我想要的是,它将您链接到一个包含团队信息的新页面。到目前为止我尝试的只是将每个团队链接到相同的详细信息页面。

这是我的gridview代码:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
    AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Team" 
    DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" 
    Height="340px" Width="776px">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:HyperLinkField DataTextField="Team" DataNavigateUrlFields="Rank" DataNavigateUrlFormatString="~/MemberPages/Details.aspx?Rank={0}"
       HeaderText="Team" SortExpression="Team" ItemStyle-Width = "150" >

        <ItemStyle Width="150px"></ItemStyle>
        </asp:HyperLinkField>

        <asp:BoundField DataField="Rank" HeaderText="Rank" SortExpression="Rank" />
        <asp:BoundField DataField="PointsPerGame" HeaderText="PointsPerGame" 
            SortExpression="PointsPerGame" />
        <asp:BoundField DataField="OpponentPointsPerGame" 
            HeaderText="OpponentPointsPerGame" SortExpression="OpponentPointsPerGame" />
        <asp:BoundField DataField="TopPlayer" HeaderText="TopPlayer" 
            SortExpression="TopPlayer" />
    </Columns>
</asp:GridView>

以下是我在cs文件中尝试将它们数据绑定到特定链接的内容:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Team"),new DataColumn("Ranking"), new DataColumn("PointsPerGame"),
        new DataColumn("OpponentPointsPerGame"), new DataColumn("TopPlayer")});

        GridView1.DataBind();
    }
}

1 个答案:

答案 0 :(得分:0)

对于特定行上的那种显示/隐藏逻辑,您需要使用GridView.RowDataBound事件。

  1. 使用TemplateField代替BoundField。
  2. 将HyperLink控件放入其中。
  3. 然后检索RowDataBound事件中的HyperLink控件。
  4. 示例代码

    <asp:TemplateField>
       <ItemTemplate>
          <asp:HyperLink runat="server" ID="MyHyperLink" Text="My Text" />
       </ItemTemplate>
    </asp:TemplateField>
    
    protected void GridView1_RowDataBound(
       Object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType == DataControlRowType.DataRow)
        {
           var myHyperLink = e.Row.FindControl("MyHyperLink") as HyperLink;   
    
           if(SOME_LOGIC) 
           {
              myHyperLink.Visible = false;
           }
        }
    }