Fahmieyz
Fahmieyz

Reputation: 255

Explain to me the function of this line of code

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

Answers (2)

sujith karivelil
sujith karivelil

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
  • The second line will give you the Master Page from which the current page is inherited. Then .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).
  • And Finally the code converts the control as an Image button and assigned to 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

wablab
wablab

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

Related Questions