I have ten group boxes in a WinForm. Each group box contains 10 text boxes, and I have defined each TextBox name. How can I get each text box using a foreach loop?
foreach(Control gb in this.Controls)
{
if(gb is GroupBox)
{
foreach(Control tb in gb.Controls)
{
if(tb is TextBox)
{
//here is where you access all the textboxs.
}
}
}
}
But if you have defined each TextBox name
What's the point to get each TextBox by a loop?
You could define a List<TextBox> to hold reference of each TextBox while creating them, then just go though the List to get access of each TextBox.
Here is my suggestion:
foreach(var groupBox in Controls.OfType<GroupBox>())
{
foreach(var textBox in groupBox.Controls.OfType<TextBox>())
{
// Do Something
}
}
Or having it in one loop:
foreach (var textBox in Controls.OfType<GroupBox>().SelectMany(groupBox => groupBox.Controls.OfType<TextBox>()))
{
// Do Something
}
try following code,
Control.ControlCollection coll = this.Controls;
foreach(Control c in coll) {
if(c != null)
}
foreach (var ctrl in gbDatabaseColumns.Controls)
{
if (ctrl is DevExpress.XtraEditors.TextEdit)
{
StoreTextEdit(config, (ctrl as DevExpress.XtraEditors.TextEdit));
}
}
foreach (Control txx in groupBox2.Controls)
{
if (txx is TextBox)
txx.Text = "";
if (txx is ComboBox)
txx.Text = "";
// if (txx is DateTimePicker)
// txx.Text = ""; Datetimepicker text can't be erased
}
Related
In my project I have 5 textboxes.
I want to find the text of each one on foreach loop.
Thant's works for me, but when I set a design on page, it doesn't work.
My code:
foreach (Control c in Page.Controls)
{
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
string text = ((TextBox)ctrl).Text;
if (!string.IsNullOrWhiteSpace(text))
{
Zone.addPermission(new User(text));
}
}
}
}
I need a way to dynamically gather all of the TextBoxes inside of a custom UserContorl in ASP.net WebForms, server-side
I thought this would work:
foreach (var control in Page.Controls)
{
var textBox = control as TextBox;
if (textBox != null && textBox.MaxLength > 0)
{
// stuff here
}
}
But it doesn't do what I thought it would, and I don't see how else to get that information.
So, how can I dynamically get all of the textboxes on the server-side of a custom UserControl in ASP.net webforms?
You need a recursive method, because not all level 1 children are necessarily text boxes (depends on the control/container hierarchy in your user control):
private IEnumerable<TextBox> FindControls(ControlCollection controls)
{
List<TextBox> results = new List<TextBox>();
foreach(var control in controls)
{
var textBox = control as TextBox;
if (textBox != null && textBox.MaxLength > 0)
{
results.Add(textBox);
}
else if(textBox == null)
{
results.AddRange(FindControls(control.Controls));
}
}
return results;
}
After you get the results you can iterate them and do whatever you need to do.
Looks like recursive is the way to go:
foreach (Control control in Page.Controls)
{
DoSomething(control);
}
// And you need a new method to loop through the children
private void DoSomething(Control control)
{
if (control.HasControls())
{
foreach(Control c in control.Controls)
{
DoSomething(c);
}
}
else
{
var textBox = control as TextBox;
if (textBox != null)
{
// Do stuff here
}
}
}
I have some Textboxes that are created dynamically --
int i = 1;
while (reader.Read())
{
System.Web.UI.WebControls.TextBox textBox = new System.Web.UI.WebControls.TextBox();
textBox.ID = reader["field_id"].ToString();
textBox.Enabled = false;
HtmlGenericControl div = new HtmlGenericControl("div");
if(i%2 != 0)
div.Attributes.Add("style", "margin-right:120px;padding-bottom:20px;");
if (i % 2 == 0)
div.Attributes.Add("style", "padding-bottom:20px;");
div.Attributes.Add("class", "inline fourcol");
div.InnerHtml = "<label>" + reader["field"] + "</label>";
div.Controls.Add(textBox);
panelId.Controls.Add(div);
textBox.Text = reader["field_value"].ToString();
++i;
}
That works fine (at least i'm sure -they show up how they should). But when i try to loop through them to enable them, or get their values, i get an "Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'. " error.
This is how i've been trying to do it --
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (System.Web.UI.WebControls.TextBox t in panel.Controls)
{
t.Enabled = true;
}
}
Thanks!
You're looping over panel.Controls, which will loop over every control in the panel. This is not necessarily the same thing as looping over everything you've added. If there was something else inside the panel that existed when you started, you will end up getting that too.
What you probably wanted was this:
foreach (var t in panel.Controls.OfType<System.Web.UI.WebControls.TextBox>())
{
t.Enabled = true;
}
You are putting each textbox inside a "div" control which is HtmlGenericControl, then inside the panel control. So first you must search for the HtmlGenericControl inside panelId.Controls
A sample code that might help you:
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (Control c in panelId.Controls)
{
if (c is HtmlGenericControl)
{
foreach (var textbox in c.Controls.OfType<TextBox>()) //ofType returns IEnumerable<TextBox>
textbox.Enabled = true;
}
}
}
There is a control inside your Panel, that is not a TextBox and could not be cast to it. You should place a breakpoint before the loop and check the panel.Control collection contents in debug mode.
You can avoid the issue if you don't specify a type in the foreach loop and do the safe cast yourself.
foreach (var t in panel.Controls)
{
var textbox = t as System.Web.UI.WebControls.TextBox;
if(textbox != null)
{
textbox.Enabled = true;
}
}
You should check if control is TextBox
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (var t in panel.Controls)
{
if (t is System.Web.UI.WebControls.TextBox)
((System.Web.UI.WebControls.TextBox)t).Enabled = true;
}
}
The Controls collection will contain a collection of all the controls in the panel - not just TextBoxes. You can iterate through all of the controls and use the as operator to perform a type cast. If the type cast succeeds then you may enable the textbox.
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (var control t in panel.Controls)
{
System.Web.UI.WebControls.TextBox textBox = control as System.Web.UI.WebControls.TextBox;
if (textBox != null)
{
control.Enabled = true;
}
}
}
you add the textbox to the div element and the div element to the panel. therefore you need to select the controls in the panel and then find the textbox.
foreach (var t in panel.Controls.Cast<Control>().SelectMany(c => c.Controls))
{
if (t is TextBox == false) continue;
((TextBox)t).Enabled = true;
}
I have some text boxes in my page. I want to get all text box values in an array and insert in to table of database.
Is there any option to work by loop
public IEnumerable<string> AllTextsFromTextboxes()
{
foreach (var control in Page.Controls.OfType<TextBox>())
{
yield return control.Text;
}
}
you can try something on these lines, if all the textbox are on the page directly
foreach(Control c in Page.Controls)
{
if (c is TextBox)
{
//get the text
}
}
This will not work for child controls for that you will have to recursively iterate
yes, you can put your controls in panel and then iterate and get value. e.g.
foreach (Control ctrl in Panel1.Controls)
{
if (ctrl.GetType().Name == "TextBox")
{
if (((TextBox)ctrl).Text != string.Empty)
{
// do stuff here
}
}
}
private void FindSelecedControl(Control control)
{
if (control is TextBox)
{
TextBox txt = (TextBox)control;
txt.Enabled = false;
}
else
{
for (int i = 0; i < control.Controls.Count; i++)
{
FindSelecedControl(control.Controls[i]);
}
}
}
foreach (Control control1 in this.Form.Controls)
{
FindSelecedControl(control1);
}
How can I use a Foreach Statement to do something to my TextBoxes?
foreach (Control X in this.Controls)
{
Check if the controls is a TextBox, if it is delete it's .Text letters.
}
If you are using C# 3.0 or higher you can do the following
foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
..
}
Without C# 3.0 you can do the following
foreach ( Control c in this.Controls ) {
TextBox tb = c as TextBox;
if ( null != tb ) {
...
}
}
Or even better, write OfType in C# 2.0.
public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class {
foreach ( object cur in e ) {
T val = cur as T;
if ( val != null ) {
yield return val;
}
}
}
foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
..
}
You're looking for
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
((TextBox)x).Text = String.Empty;
}
}
The trick here is that Controls is not a List<> or IEnumerable but a ControlCollection.
I recommend using an extension of Control that will return something more..queriyable ;)
public static IEnumerable<Control> All(this 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().OfType<TextBox>)
{
// Apply logic to the textbox here
}
Also you can use LINQ. For example for clear Textbox text do something like:
this.Controls.OfType<TextBox>().ToList().ForEach(t => t.Text = string.Empty);
foreach (Control X in this.Controls)
{
if (X is TextBox)
{
(X as TextBox).Text = string.Empty;
}
}
You can do the following:
foreach (Control X in this.Controls)
{
TextBox tb = X as TextBox;
if (tb != null)
{
string text = tb.Text;
// Do something to text...
tb.Text = string.Empty; // Clears it out...
}
}
A lot of the above work.
Just to add. If your textboxes are not directly on the form but are on other container objects like a GroupBox, you will have to get the GroupBox object and then iterate through the GroupBox to access the textboxes contained therein.
foreach(Control t in this.Controls.OfType<GroupBox>())
{
foreach (Control tt in t.Controls.OfType<TextBox>())
{
// do stuff
}
}
Just add other control types:
public static void ClearControls(Control c)
{
foreach (Control Ctrl in c.Controls)
{
//Console.WriteLine(Ctrl.GetType().ToString());
//MessageBox.Show ( (Ctrl.GetType().ToString())) ;
switch (Ctrl.GetType().ToString())
{
case "System.Windows.Forms.CheckBox":
((CheckBox)Ctrl).Checked = false;
break;
case "System.Windows.Forms.TextBox":
((TextBox)Ctrl).Text = "";
break;
case "System.Windows.Forms.RichTextBox":
((RichTextBox)Ctrl).Text = "";
break;
case "System.Windows.Forms.ComboBox":
((ComboBox)Ctrl).SelectedIndex = -1;
((ComboBox)Ctrl).SelectedIndex = -1;
break;
case "System.Windows.Forms.MaskedTextBox":
((MaskedTextBox)Ctrl).Text = "";
break;
case "Infragistics.Win.UltraWinMaskedEdit.UltraMaskedEdit":
((UltraMaskedEdit)Ctrl).Text = "";
break;
case "Infragistics.Win.UltraWinEditors.UltraDateTimeEditor":
DateTime dt = DateTime.Now;
string shortDate = dt.ToShortDateString();
((UltraDateTimeEditor)Ctrl).Text = shortDate;
break;
case "System.Windows.Forms.RichTextBox":
((RichTextBox)Ctrl).Text = "";
break;
case " Infragistics.Win.UltraWinGrid.UltraCombo":
((UltraCombo)Ctrl).Text = "";
break;
case "Infragistics.Win.UltraWinEditors.UltraCurrencyEditor":
((UltraCurrencyEditor)Ctrl).Value = 0.0m;
break;
default:
if (Ctrl.Controls.Count > 0)
ClearControls(Ctrl);
break;
}
}
}
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
((TextBox)x).Text = String.Empty;
//instead of above line we can use
*** x.resetText();
}
}
Check this:
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
x.Text = "";
}
}
simple using linq, change as you see fit for whatever control your dealing with.
private void DisableButtons()
{
foreach (var ctl in Controls.OfType<Button>())
{
ctl.Enabled = false;
}
}
private void EnableButtons()
{
foreach (var ctl in Controls.OfType<Button>())
{
ctl.Enabled = true;
}
}
Even better, you can encapsule this to clear any type of controls you want in one method, like this:
public static void EstadoControles<T>(object control, bool estado, bool limpiar = false) where T : Control
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Enabled = estado;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.Enabled = estado;
if (!limpiar) return;
{
foreach (var textEdits in ((T)control).Controls.OfType<TextEdit>()) textEdits.Text = string.Empty;
foreach (var textLookUpEdits in ((T)control).Controls.OfType<LookUpEdit>()) textLookUpEdits.EditValue = #"-1";
}
}
private IEnumerable<TextBox> GetTextBoxes(Control control)
{
if (control is TextBox textBox)
{
yield return textBox;
}
if (control.HasChildren)
{
foreach (Control ctr in control.Controls)
{
foreach (var textbox in GetTextBoxes(ctr))
{
yield return textbox;
}
}
}
}
I found this to work very well, but initially I have my textboxes on a panel so none of my textboxes cleared as expected so I added
this.panel1.Controls.....
Which got me to thinking that is you have lots of textboxes for different functions and only some need to be cleared out, perhaps using the multiple panel hierarchies you can target just a few and not all.
foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
..
}