Thursday 21 August 2008

FindControl Causes Null Reference Exception with NMock

When using NMock on code that uses FindControl, a null reference exception is thrown:

PlaceHolder placeHolder =

(PlaceHolder) _view.MyPanel.FindControl("myplaceholder");

You could use the indexer instead:

PlaceHolder placeHolder =

(PlaceHolder) _view.MyPanel.Controls[0];

But if you insert another control in the panel, you break your code. So, the alternative is to loop through the controls and find a match by ID:

ControlCollection ctrls = _view.MyPanel.Controls;

foreach( Control ctrl in ctrls )
{
if( ctrl.ID == "myplaceholder" )
{
placeHolder = (PlaceHolder) ctrl;
break;
}
}

No comments: