0

I have a listview control which is populated with data from a database. I have used the label to display that data. Now I need to use the value of that label in some other place. I am trying to access the text value of the label control but it says

Object reference not set to an instance of an object.

But I do have value in the label.

<asp:ListView ID="msg_list" runat="server">
   <ItemTemplate>
    <table>
      <tr class="myitem">
        <td>
            <asp:Label ID="reg_id_reply" runat="server" Text="helo" Visible="false"  />
             <asp:Label role="menuitem" ID="msg_lbl" runat="server" text='<%#Eval("msg")%>' /><i style=" color:Gray; " >  from   
             <asp:Label ID="tme" runat="server" Text='<%#Eval("name")%>' />
             <i> on </i>
             <asp:Label ID="tmelbl" runat="server" Text='<%#Eval("tme")%>'/>
              <a id="msg-reply" class="btn button" data-toggle="modal" data-target="#msg-rply" style="cursor:pointer;" ><i class="glyphicon glyphicon-share-alt white"> </i></a>  </td>

              <hr style=" margin-top:1px; margin-bottom:1px; " />
      </tr>
     </table>
     <%--<hr style=" margin-top:1px; margin-bottom:1px; " />--%>
   </ItemTemplate>
  </asp:ListView>

This is how i tried to access the text of the label.Note that the code below is inside a button click event onClick of buttom.

Label mylbl = (Label)msg_list.FindControl("reg_id_reply");
string rid = mylbl.Text;
user35
  • 478
  • 1
  • 8
  • 21

1 Answers1

0

According to the description for Control.FindControl Method (String):

This method will find a control only if the control is directly contained by the specified container.

The direct container that your label is contained within is the ItemTemplate. Therefore you may need to build a recursive search for your label if you are starting with the listview. You could try the following code that is suggested from this MSDN page:

private Control FindControlRecursive(Control rootControl, string controlID)
{
    if (rootControl.ID == controlID) return rootControl;

    foreach (Control controlToSearch in rootControl.Controls)
    {
        Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
        if (controlToReturn != null) return controlToReturn;
    }
    return null;
}

However also note that the listview may change the id values of components in the item template. If you know the item index you want then you can use the method suggested in this post:

var theLabel = this.ChatListView.Items[<item_index>].FindControl("reg_id_reply") as Label;
Community
  • 1
  • 1
Ben
  • 2,951
  • 3
  • 31
  • 44