I have master page and 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())
{
...
}
Related
I've found a few answers around that work fine with modifying .Text, .Checked values and so, but none of them worked when I tried changing the .Value property. I can't get that to work on progress bars.
Last I tried:
foreach (Control c in this.Controls)
{
if (c.Name == "test" && c is ProgressBar)
{
((ProgressBar)c).Value = 23;
}
}
Am I missing a using statement or something?
Assuming that your progressbar control is named "test" (all lowercase letters) and is placed directly on the surface of your form (not inside a groupbox,panel or other control container) then this code should work and simplify your work
foreach (var c in this.Controls.OfType<ProgressBar>().Where(x => x.Name == "test")
{
c.Value = 23;
}
instead if the ProgressBar is placed inside a control container (like a panel) the above code should be changed to loop over the controls collection of the container
foreach (var c in this.panel1.Controls.OfType<ProgressBar>().Where(x => x.Name == "test")
{
c.Value = 23;
}
As pointed out in the comment by KingKing, if you are absolutely sure that a control named "test" exists in your groupbox then a simple lookup in the controls collection should result in your progressbar. Looping is not necessary in this case
ProgressBar pb = this.groupBox1.Controls["test"] as ProgressBar;
if(pb != null) pb.Value = 23;
The trick here is that Controls is not a List<> or IEnumerable but a ControlCollection.
I recommend using an extension of Control. Add this class to your project:
public static class ControlExtensionMethods
{
public static IEnumerable<Control> All(this System.Windows.Forms.Control.ControlCollection controls)
{
foreach (Control control in controls)
{
foreach (Control grandChild in control.Controls.All())
yield return grandChild;
yield return control;
}
}
}
Then you can do :
foreach(var textbox in this.Controls.All())
{
// Apply logic to a control
}
Source: Click
I've used this code before in another program, but now I'm having trouble understanding why it won't run the code after my second line.
foreach (Control c in Controls)
if (c.GetType() == typeof(TextBox)) //doesn't run any further
{
if ((string)c.Tag == "Filled")
{
...
}
...
}
I'm either missing some minor little detail or something else is incorrect. Any ideas?
EDIT: my textboxes are inside a panel.
It might be simpler to do this:
foreach ( TextBox tb in this.Controls.OfType<TextBox>())
{
if ((string)tb.Tag == "Filled")
// .....
}
When you call Control.Controls, it will only return the controls at the outermost level. It won't recursively descend into any container controls that hold other controls.
If your controls are in another container, you will need to use that container's .Controls property instead.
Alternatively you can generalize it by writing a method to recursively return all the controls from the parent and all it's children, like so:
public IEnumerable<Control> AllControls(Control container)
{
foreach (Control control in container.Controls)
{
yield return control;
foreach (var innerControl in AllControls(control))
yield return innerControl;
}
}
You can then use that instead of Control.Controls as follows:
private void test() // Assuming this is a member of a Form other class derived from Control
{
var textboxesWithFilledTag =
AllControls(this).OfType<TextBox>()
.Where(tb => (string) tb.Tag == "Filled");
foreach (var textbox in textboxesWithFilledTag)
Debug.WriteLine(textbox.Text);
}
As the comment says, I'm assuming that the test() method is a member of your Form or another class derived from Control. If it isn't, you will have to pass the parent control to it:
private void test(Control container)
{
var textboxesWithFilledTag =
AllControls(container).OfType<TextBox>()
.Where(tb => (string) tb.Tag == "Filled");
foreach (var textbox in textboxesWithFilledTag)
Debug.WriteLine(textbox.Text);
}
The following method has identical results to the one above, for reference (and is more readable IMHO):
private void test(Control container)
{
foreach (var textbox in AllControls(container).OfType<TextBox>())
if ((string)textbox.Tag == "Filled")
Debug.WriteLine(textbox.Text);
}
For your code, your button click handler might look something like this:
void button1_Click(object sender, EventArgs e)
{
foreach (var c in AllControls(this).OfType<TextBox>())
{
if ((string) c.Tag == "Filled")
{
// Here is where you put your code to do something with Textbox 'c'
}
}
}
Note that you also need the AllControls() method, of course.
To get all controls (not only the direct children of the form) you can use this recursive Linq
Func<Control, IEnumerable<Control>> allControls = null;
allControls = c => new Control[] { c }
.Concat(c.Controls.Cast<Control>()
.SelectMany(x=>allControls(x)));
Now you can filter the TextBoxes
var tbs = allControls(this).OfType<TextBox>()
.Where(t=>(string)t.Tag=="Filled")
.ToList();
Better use if (c is TextBox).
Furthermore, if you want to know why your code breaks, use try/catch
I'd recommend to use following syntax:
foreach (Control c in Controls)
if (c is TextBox)
Are you setting tag property from yourself. This is a string type of property.so you can try this:
if (c.Tag == "Filled")
{
Console.WriteLine(c.Name);
}
if you want to check that text box is not empty then you can simply try this :
if (c.Text.Trim().Length == 0)
{
Console.WriteLine(c.Name);
}
the following one doesn't work:
foreach (Control control in Controls) {
if (control is DropDownList) {
DropDownList list = control as DropDownList;
...
}
}
PS: My class extends System.Web.UI.Page
You just need to replace Controls with Form.Controls
foreach (Control c in Form.Controls)
{
if (c is DropDownList)
{
// do something
}
}
Or you can use this extension:
public static IEnumerable<T> AllControls<T>(this Control startingPoint) where T : Control
{
bool hit = startingPoint is T;
if (hit)
{
yield return startingPoint as T;
}
foreach (var child in startingPoint.Controls.Cast<Control>())
{
foreach (var item in AllControls<T>(child))
{
yield return item;
}
}
}
Then you can use it for search of any type of System.Web.UI.Control within specific control. In case of DropDownList you can use it like:
IEnumerable<DropDownList> allDropDowns = this.pnlContainer.AllControls<DropDownList>();
this will find all drop downs within Panel control with ID="pnlContainer".
The problem is that some of the DropDownList controls may be nested in other controls.
If you page has a panel and all of your controls are in that panel the page's control array will only have that panel and all of the control will be in the Panel's control array.
The link that ajax81 linked to will work well.
I have a login control and at is nested 2 deep in a header control
i.e Page --> Header Control --> Login Control. I cannot get a reference to the control on the page using FindControl. I want to be able to set the visible property of the control like
if (_loginControl != null)
_loginControl.Visible = false;
I ended up using a recursive FindControl method to find the nested control.
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Are you needing to disable/hide the User Control from the ASP.NET page it resides on (or does the User Control exist on a master page, say)? If it's in the same page, then in your ASP.NET page's code-behind you'd do:
MyUserControlsID.Visible = false
Where MyUserControl is the ID of your User Control. To determine the ID of your User Control look at the markup of your .aspx page and you will see something like this:
<uc1:UserControlName ID="MyUserControlsID" runat="server" ... />
Happy Programming!
A good way would be to use:
Page.FindControl()
if that yields null, the control is not there.
Try calling this.FindControl("_loginControl") or this.Page.FindControl("_loginControl").
See MSDN for method details:
http://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol.aspx
The login control, if it's registered in the markup, will also be an instance member of your codebehind page; you can refer to it from the codebehind class as if it were a normal member, using the same name you provided as the ID (I do recommend using codebehinds for most logic, instead of inlining code in the markup, BTW).
You can also use the FindControl() method of your page, which will search its control subtree for a control with a given ID. That takes longer, so I would recommend the first option unless the logic control is added dynamically and you don't always know it's there.
private List<Control> GetAllNestedUserControl(Control ph)
{
List<Control> Get = new List<Control>();
foreach (var control in ph.Controls)
{
if (control is UserControl)
{
UserControl uc = control as UserControl;
if (uc.HasControls())
{
Get = GetAllNestedUserControl(uc);
}
}
else
{
Control c = (Control)control;
if (!(control is LiteralControl))
{
Get.Add(c);
}
}
}
return Get;
}
just call this code from you any parent page and then get any control by the following code
List<Control> Get = GetAllNestedUserControl(ph);
Label l = (Label)Get.Find(o => o.ID == "lblusername");
l.Text = "changed from master";
I have a page, which contains a table, with a couple of rows, and in that row there are checkboxes.
Now the thing I want, is to loop trough all checkboxes to see if they are checked or not.
This is my current approach:
foreach (Control c in Page.Controls)
{
if(c is Checkbox){
}
}
Now the problem is that I receive only 2 controls, the page and the Table. So the checkboxes are in:
Table -> TableRow -> TableCell -> CheckBox
Is there a way to get ALL controls on a page, instead of having to nest into it to get out the controls?
control.Controls will return the first level child controls only. For details, check this question.
Since the controls are hierarchical, every control sees only it's child controls. You have to iterate through every control to get them all.
You can find an example on how to do it here:
http://www.atrevido.net/blog/CommentView,guid,c792adbf-ce0a-4bf9-a61c-ca1a4296d0ea.aspx
A Control can act as a parent to a collection of controls as in your case .You should Iterate through the child of the parent control you are using in you page.
refer http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controls%28VS.71%29.aspx
I just did a nested foreach loop like this:
List<Control> allControls = new List<Control>();
List<string> selectedIDs = new List<string>();
foreach (Control c in this.pnlTable.Controls)
{
allControls.Add(c);
if (c.Controls.Count > 0)
{
foreach (Control childControl in c.Controls)
{
allControls.Add(childControl);
if (childControl.Controls.Count > 0)
{
foreach (Control childControl2 in childControl.Controls)
{
allControls.Add(childControl2);
if (childControl2.Controls.Count > 0)
{
foreach (Control childControl3 in childControl2.Controls)
{
allControls.Add(childControl3);
}
}
}
}
}
}
}
foreach (Control control in allControls)
{
if (control is CheckBox)
{
if (((CheckBox)(control)).Checked)
{
selectedIDs.Add(((CheckBox)(control)).ID);
}
}
}
Depending of the depth of the control I added a if and foreach..
Hope this helps someone else with the same issue...