0

I have a repeater with some labels, they all work fine except the last one leading to NullReferenceException. Probably there is a banal sintax mistake... but i can't see it!

<asp:Repeater ID="ticketrep1" runat="server" OnItemDataBound="TicketsRep_ItemDataBound">
     <ItemTemplate>
          <asp:Label runat="server" ID="tksubject" Style="font-weight:bold;" />
          <asp:Label runat="server" ID="breadctrail" Style="font-weight:bold;" />
     </ItemTemplate>
</asp:Repeater>

Code Behind:

protected void TicketsRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label tksubject = (Label)e.Item.FindControl("tksubject");
            tksubject.ClientIDMode = ClientIDMode.Static;
            tksubject.ID = "tksubject" + Ticket.idTicket;
            tksubject.Text = Ticket.oggetto;

            Label breadctrail = (Label)e.Item.FindControl("breadctrail");
            breadctrail.ClientIDMode = ClientIDMode.Static;
            breadctrail.ID = "breadcrumbtrail" + Ticket.idTicket;
            breadctrail.Text = Ticket.categoria.ToString();
    }
}

NullReferenceException appears in the first line after declaration: breadctrail.ClientIDMode = ClientIDMode.Static;

so I tried to comment it and the error simply pass to the second line. breadctrail appears Null.

Thank you all.

Edit for "possible duplicate": Of two (and more) labels with apparently the same syntax, only one gives an error. Why?

Thank you again.

Dizi0
  • 1
  • 2
  • Probably `e.Item` doesn't have any `Control` named "breadctrail". Try to double check that. – andresantacruz Aug 23 '19 at 10:19
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Diado Aug 23 '19 at 10:20
  • look at the registration of the event handler. what is sender value? what is the e value in your debug session? – Barış Akkurt Aug 23 '19 at 10:25
  • Do you know what `ClientIDMode.Static` does? Hint: you cannot have multipe controls with the same ID on a page... – VDWWD Aug 23 '19 at 18:53

1 Answers1

0

Simply this code below gives you null:

Label breadctrail = (Label)e.Item.FindControl("breadctrail");

It cannot find label with name breadctrail.

You can do this:

Label breadctrail = (Label)e.Item.FindControl("breadctrail");

if (breadctrail != null) {
   breadctrail.ClientIDMode = ClientIDMode.Static;
   breadctrail.ID = "breadcrumbtrail" + Ticket.idTicket;
   breadctrail.Text = Ticket.categoria.ToString();
} else {
   // Do something when there is no label with this name
}
XardasLord
  • 1,764
  • 2
  • 20
  • 45