简体   繁体   中英

FindControl not working in Listview Null exception

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM