FindControl in Master Page

Accessing a control  can be a problem in codebehind in ASP.NET. However you will often need to access the control  because you want to change the text property of a textbox or changing certain value. If the control is directly laying in the page itself, then you can directly access it via mycontrolID But if the control is sitting inside a gridview or formview or panel, you can not access that control directly. In fact that control is invisible to codebehind file. To access that you have to use GridView.FindControl(controlname) to find the control and only then you can change its value, provided it did finds the control. If you do not know the exact structure of where the control is, you are at a disadvantage. In that case, there is a user define function that you have to use to find your control. One such method is this

private  Control FindControlIterative(Control root, string id)
{
Control ctl = root;

LinkedList<Control> ctls = new LinkedList<Control>();
while (ctl != null)
{
if (ctl.ID == id) return ctl;
foreach (Control child in ctl.Controls)
{
if (child.ID == id)
return child;

if (child.Controls.Count > 0)
ctls.AddLast(child);
}
if (ctls.Count > 0)
{
ctl = ctls.First.Value;
ctls.Remove(ctl);
}
else
ctl = null;
}
return null;
}

Copy this code the code behind at the bottom of the page and now this function will be available to all the functions in your codebehind.

To use the funcation, use this syntax

TextBox myTextBox = (TextBox)this.FindControlIterative (mygridview, “txtTextBox”);

Note here that mygridview is the top level control in the page that is recognized on the page. It will be in most case the container object that contains your particular control.  If your control is other than TextBox, you will have to typecast it as that type of control.

Caution

Caution need to be made

  • ASP:Textbox: It must be ASP.NET control. FindControl does not work with regular HTML controls
  • SPAN:Some html tags for example SPAN might have some trouble with it too. If a control is not supposed to have childeren, FindControlRecursive will probably not find it. span.innerthtml did not work in my case.
  • Table: I am not sure if it is suppose to work with table. It did not work for me even with <asp:table …> Link. TableRow, TableCell might be needed, not sure.
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s