0
Label lbl = dgi.FindControl("LBL_MyLabel") as Label; 

This works most of the time, but sometimes lbl is null after FindControl was called. I am wondering how this could happen. It should either be there or not? Any ideas?

The label is defined like this:

<asp:Label ID="LBL_MyLabel" runat="server"></asp:Label>

Thanks :-)

grady
  • 12,281
  • 28
  • 71
  • 110

1 Answers1

1

What's the broader context of the code around the call to FindControl? This error is commonly experienced when iterating through the rows in the grid (such as in the RowDataBound event) without conditionally checking what the row type is:

if (e.row.RowType == DataControlRowType.DataRow)
{
  // your code
}

Wrapping it in that conditional will skip header/footer rows, which probably don't have your label control in them.

David
  • 208,112
  • 36
  • 198
  • 279
  • Its inside a TemplateColumn in my grid and its called in the ItemDataBound method of the grid. There is no special if(something) around it. – grady Apr 06 '11 at 10:22
  • @grady: `ItemDataBound`? Sounds like a classic `DataGrid`. It also sounds like it's the same issue, just a different syntax. For that you'd probably want a conditional like: `if((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))` – David Apr 06 '11 at 10:40
  • @grady: Not sure. Is there anything different in an alternating item template? When you debug, what controls are found within the item? Conversely, if you set the conditional to only handle `ItemType`s of `ListItemType.Item` then does it catch all your rows? – David Apr 06 '11 at 12:00
  • How do I know the controls in an item? – grady Apr 06 '11 at 12:50
  • @grady: I don't have anything handy to test this, but `e` should be of type `DataGridItem` which should have a `Controls` property. That would be the best place to start. I imagine the control hierarchy would be available in there, but I'm not 100% certain. It might get cloudy depending on how dynamic the whole thing is and at what point things are bound/created. – David Apr 06 '11 at 13:09