Jes Sie

Jes Sie

  • 698
  • 1.2k
  • 266.1k

Call Hyperlink inside a Datalist control from code behind using C#

Feb 15 2022 9:07 AM

I have a file path from a database (~/Dashboard/YearbookRepository/SY2122A/SY 2019-2020.pdf). I bind it in the DataList control using a hyperlink control.

How can I call the hyperlink from code behind using a button? 

Below is my aspx file

<asp:DataList ID="DataList1" runat="server" Visible="true" AutoGenerateColumns="false" CssClass="table table-condensed" RepeatColumns="3"
    CellSpacing="1" RepeatDirection="Horizontal">
    <ItemTemplate>
        <div class="row text-center">
            <div class="col-md-2 text-center">
                <asp:Button ID="btnSelect" runat="server" Text='<%# Eval("SchoolYear") %>' CssClass="btn btn-primary font"
                    Width="190px" Height="100px" UseSubmitBehavior="False" CommandName="Selected" OnClick="btnSelect_Click"/>

                  <asp:HyperLink runat ="server" CssClass="btn btn-primary"  ID="hlYearbook"
                      text='<%# DataBinder.Eval(Container.DataItem,"FilePath") %>' Visible="false"></asp:HyperLink>
            </div>
        </div>
    </ItemTemplate>
</asp:DataList>

Below is my code behind

protected void btnSelect_Click(object sender, EventArgs e)
{
    DataListItem item = (DataListItem)(sender as Button).NamingContainer;
    HyperLink hlYearbook = item.FindControl("hlYearbook") as HyperLink;
    string url = hlYearbook.Text;
    hlYearbook.NavigateUrl = url;
    hlYearbook.Target = "_blank";
}

If I click the button, the hyperlink does not work. Thank you in advance.


Answers (4)