0
protected void PassSessionVariable_Click(object sender, EventArgs e)
{
    String strLocationID = livTour.FindControl("lblLocationID").ToString();
}

For some reason, the FindControl is getting a null exception. Any particular reasons?

Here is the code for my Listview. The find control is not finding the LocationID label.

<%--Create datasource for ListView for Tour Locations.--%>
<asp:SqlDataSource runat="server" ID="sdsListViewTour"
    ConnectionString="<%$ConnectionStrings:2020LJCDT %>"
    OldValuesParameterFormatString="original_{0}"
    SelectCommand="SELECT LocationID, Location, Image
                     FROM Location
                    Order BY City;">
</asp:SqlDataSource>

<%--Listview--%>
<asp:ListView runat="server" ID="livTour"
    DataKeyNames="Location" 
    DataSourceID="sdsListViewTour">

    <ItemTemplate>

        <div class="container p-1 bg-light">

            <asp:LinkButton runat="server" ID="PassSessionVariable" OnClick="PassSessionVariable_Click">
                <div class="row border-top border-bottom border-secondary" style="padding-top: 5px; padding-bottom: 5px; padding-left: 20px;">

                    <asp:Label runat="server" ID="lblLocationID" Text='<%# Eval("LocationID") %>' />

                    <div class="col text-center" style="margin: auto; color: #2699FB;">
                        <asp:Label runat="server" CssClass="font-weight-bold" Text='<%# Eval("Location") %>' />
                    </div>

                    <div class="col text-center">
                        <asp:Image runat="server" CssClass="rounded" ImageUrl='<%# "~/Image/Location/" + Eval("Image") %>' />
                    </div>

                </div>
            </asp:LinkButton>

        </div>

    </ItemTemplate>
</asp:ListView>
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
Isiah Jones
  • 94
  • 1
  • 12

1 Answers1

0

You can find location label via BindingContainer of sender as follow:

protected void PassSessionVariable_Click(object sender, EventArgs e)
{
    var locationLabel = (((Control)sender).BindingContainer.FindControl("lblLocationID") as Label);

    String strLocationID = locationLabel.Text;
}

In this case BindingContainer indicates the row of ListItem that you click. So that you can find location label in this row.

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28