Hi I have master page & its content page. I want to get the textboxes situated on Content page. How can i get them in C# code behind of Content page?
Access it by using it's ID:
Markup:
<asp:TextBox runat="server" ID="myTextBox"></asp:TextBox>
Code behind:
myTextBox.Text = "This is a text!";
Note that you need to add runat="server"
for it to be accessible.
Edit
After your comment I think I understand where you're getting at. You'll need to traverse through all controls down the control tree to find all TextBoxes.
Here is a recursive implementation:
public List<Control> FindControls(Control root, Type type)
{
var controls = new List<Control>();
foreach (Control ctrl in root.Controls)
{
if (ctrl.GetType() == type)
controls.Add(ctrl);
if (ctrl.Controls.Count > 0)
controls.AddRange(FindControls(ctrl, type));
}
return controls;
}
To get all TextBoxes in a page you'll call it with Page as root Control:
var allTextBoxes = FindControls(Page, typeof(TextBox));
The above example is to clarify the idea of how you should proceed. I'd do it a bit differently by using an Extension Method:
public static class ExtensionMethods
{
public static IEnumerable<Control> FindControls(this Control root)
{
foreach (Control ctrl in root.Controls)
{
yield return ctrl;
foreach (Control desc in ctrl.FindControls())
yield return desc;
}
}
}
Now you can use it directly on any control and even apply Linq on the result since it's an IEnumerable.
This will get you an array of all controls in a page:
var allControls = this.FindControls().ToArray();
To get an array of all TextBox controls:
var allTextBoxes = this.FindControls()
.OfType<TextBox>().ToLArray<TextBox>();
and to get a list of TextBoxes with a specific id:
var myTextBox = this.FindControls()
.OfType<TextBox>()
.Where<TextBox>(tb => tb.ID.Equals("textBox1")).ToList<TextBox>();
You can also use it in foreach statements:
foreach (Control c in this.FindControls())
{
...
}