Reputation: 255
While I was searching for answer to my problem in MasterPage .FindControl in Class, I stumbled across this solution but what do these lines of code do? Can anyone explain to me?
var pageHandler = HttpContext.Current.CurrentHandler;
Control ctrlHull = ((Page)pageHandler).Master.FindControl("imgbtnHull");
ImageButton imgBtnHull = (ImageButton)ctrlHull;
I'm self-teaching myself C# programming so I have little knowledge about this language.
Upvotes: 1
Views: 87
Reputation: 29036
Beware of getting NullReference in this line (ImageButton)ctrlHull
So i suggest you to check for null
before convert ctrlHull
as (ImageButton)
. Let me explain the rest of code:
The expected action to be performed by this snippet is to find an ImageButton named
imgbtnHull
in the master page of the current page.
This can be achieved with the help of following :
HttpContext.Current.CurrentHandler
: HttpContext itself is an
object, you can access the current serving page from
HttpContext.Current.CurrentHandler
since the Page implements
IHttpHandler.FindControl
Searches the current naming container for a server control with the specified id parameter. which will return The specified control, or null if the specified control does not exist(Here comes the first point that i have mentioned, the NullReference
).imgBtnHull
. Here is the modified code:
var pageHandler = HttpContext.Current.CurrentHandler;
Control ctrlHull = ((Page)pageHandler).Master.FindControl("imgbtnHull");
if(ctrlHull !=null)
{
ImageButton imgBtnHull = (ImageButton)ctrlHull;
// Proceed with imgBtnHull
}
Upvotes: 1
Reputation: 1743
// Get the page that is handling the current request.
var pageHandler = HttpContext.Current.CurrentHandler;
// Find the control named "imgbtnHull" on the master page.
Control ctrlHull = ((Page)pageHandler).Master.FindControl("imgbtnHull");
// Cast the control to type ImageButton.
ImageButton imgBtnHull = (ImageButton)ctrlHull;
So basically, it's grabbing a reference to the ImageButton named "imgbtnHull" that is defined within the current page's Master Page.
Upvotes: 2