I thought this would work. But it's not working. It's never getting inside of if (c is HtmlInputCheckBox)
private string GetAllCheckBoxes(ControlCollection controls)
{
StringBuilder sb = new StringBuilder();
foreach (Control c in controls)
{
if (c.HasControls())
{
GetAllCheckBoxes(c.Controls);
}
else
{
if (c is HtmlInputCheckBox)
{
CheckBox cb = c as CheckBox;
if (cb.Checked)
{
sb.Append(cb.ID + "_1");
}
else
{
sb.Append(cb.ID + "_0");
}
}
}
}
return sb.ToString();
}
update: c is throwing somesort of error.
Parent = {InnerText = '((System.Web.UI.HtmlControls.HtmlContainerControl)(((System.Web.UI.HtmlControls.HtmlGenericControl)(c.Parent)))).InnerText' threw an exception of type 'System.Web.HttpException'}
HtmlInputCheckBox and CheckBox are different classes and do not inherit from the other. An is test on one won't work for the other and vice versa. Sounds like the control is probably an instance of a CheckBox so change the conditional to:
if (c is CheckBox)
Related
i cant find anything to fix this error :/ im trying to 2 letter combinations(ex. aa,ba,cb) to multiplier like(aa*3=4*3 ba*2=3,5*2).
my codes are;
string[] dersler = new string[9];
double[] kredi = new double[9];
double[] krediSonuclari = new double[9];
double derscarp(double s1, double s2)
{
return s1 * s2;
}
private void button1_Click(object sender, EventArgs e)
{
int i=0;
int j = 0;
foreach (TextBox item in Controls)
{
if (item.Name.Substring(0,7)=="txtders")
{
dersler[i] = Convert.ToString(item.Text);
i++;
}
}
foreach (TextBox item in Controls)
{
if (item.Name.Substring(0, 8) == "txtkredi")
{
kredi[j] = Convert.ToDouble(item.Text);
j++;
}
}
double toplam =0;
for (int k = 0; k < 9; k++)
{
foreach (TextBox item in Controls)
Controls contains some controls that aren't textboxes.
Your foreach statement tells the compiler to cast each item in the collection to TextBox, which won't work.
Instead, you can call .OfType<TextBox>(), which will return a filtered subsequence of the collection that only contains TextBox instances.
When you do this:
foreach (TextBox item in Controls)
{
if (item.Name.Substring(0,7)=="txtders")
{
dersler[i] = Convert.ToString(item.Text);
i++;
}
}
you assume every control in your form is a textbox, which is probably not true. Because of that it will try to cast your Label controls as a TextBox, fail and throw an error.
Try this instead:
foreach (Control ctrl in Controls)
{
TextBox item = ctrl as TextBox;
if (item != null)
{
if (item.Name.Substring(0,7)=="txtders")
{
dersler[i] = Convert.ToString(item.Text);
i++;
}
}
}
replace
foreach (TextBox item in Controls) //implicit cast.
}
with
foreach (Control ctrl in Controls)
if (ctrl is TextBox){
TextBox tb = (Textbox)ctrl; //explicit cast
}
}
foreach does not automagically pick out the cherr... ehm... Textboxes of the Control Collection, so for every CONTROL inside the collection, that is NOT a TextBox the implicit cast will fail.
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);
}
I need to save and restore settings for specific controls on a form.
I loop thru all controls and return the one whose name matches the one I want, like so:
private static Control GetControlByName(string name, Control.ControlCollection Controls)
{
Control thisControl = null;
foreach (Control c in Controls)
{
if (c.Name == name)
{
thisControl = c;
break;
}
if (c.Controls.Count > 0)
{
thisControl = GetControlByName(name, c.Controls);
if (thisControl != null)
{
break;
}
}
}
return thisControl;
}
From this I can determine the type of control and therefore the property that should be / has been stored.
This works well unless the control is one of the ToolStrip family which has been added to a toolstrip. e.g.
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblUsername, // ToolStripLabel
this.toolStripSeparator1,
this.cbxCompany}); // ToolStripComboBox
In this case I can see the control I'm interested in (cbxCompany) when debugging, but the name property has no value so the code does not match to it.
Any suggestions on how I can get to these controls too?
Cheers,
Murray
Thanks for your help guys.
Pinichi set me on the right track, I was checking toolStrip.Controls - should have been toolStrip.Items
The code below now works perfectly for me:
private static Control GetControlByName(string controlName, Control.ControlCollection parent)
{
Control c = null;
foreach (Control ctrl in parent)
{
if (ctrl.Name.Equals(controlName))
{
c = ctrl;
return c;
}
if (ctrl.GetType() == typeof(ToolStrip))
{
foreach (ToolStripItem item in ((ToolStrip)ctrl).Items)
{
if (item.Name.Equals(controlName))
{
switch (item.GetType().Name)
{
case "ToolStripComboBox":
c = ((ToolStripComboBox)item).Control;
break;
case "ToolStripTextBox":
c = ((ToolStripTextBox)item).Control;
break;
}
if (c != null)
{
break;
}
}
}
}
if (c == null)
c = GetControlByName(controlName, ctrl.Controls);
else
break;
}
return c;
}
Try This:
//for toolstrip
if (ctrl is ToolStrip)
{
ToolStrip ts = ctrl as ToolStrip;
foreach (ToolStripItem it in ts.Items)
{
if (it is ToolStrienter code herepSeparator)
{
//-------------------------
}
else
{
//do something
}
}
}//---------------
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>()) {
..
}