Changing multiple control properties at once - c#

I'm needing to change a bunch of properties in a large amount of controls. I'm having trouble getting it to work. Am I on the right track?
foreach(var c in this.Controls.OfType<Label>())
{
c.Text = "test";
}
What's happening is var c is just creating a new object and not editing the existing one. How can I access the real control?

you can try this
List<Control> controls = Controls.OfType<Label>().Cast<Control>().ToList();
foreach (Control m in controls)
{
m.Text = "test";
}

Try the following:
foreach(var c in this.Controls)
{
var label = c as Label;
if(label != null) label.Text = "test";
}

Related

Clearing MOST labels on form, NOT all

I need to clear 32 labels on my windows form application, there are other labels present but I do NOT want to clear these. Is there a more efficient and less coded way to do this? My code for this at the moment is as follows using a method: (snippet)
private void ClearFields()
{
label50.Text = string.Empty;
label51.Text = string.Empty;
label52.Text = string.Empty;
label53.Text = string.Empty;
label54.Text = string.Empty;
label55.Text = string.Empty;
// Down to label82
}
I have researched but it's always clearing ALL labels/textboxes.
You could add an object to the Tag of the Label you want to clear.
Label label50 = new Label();
bool deleteMe = true;
label50.Tag = deleteMe;
Then just iterate over your labels and clear all where the Tag is true:
foreach(Label lbl in myLabels)
{
if(lbl.Tag != null && lbl.Tag is bool && (bool)lbl.Tag == true)
{
lbl.Text = String.Empty;
}
}
Try following line:
foreach (Label _label in this.Controls.OfType<Label>().Where(a => a.Name != "Lable32").Select(a => a).ToArray())
_label.Text = string.Empty;
Add non removal lable in where condition if there are many. Here except lable32 all lable text will set to empty.
I would recomend you to place all the labels that need to be cleared in some kind of cointainer. That way you can do something of the sort:
foreach (var child in container.Children)
{
if (child is Label)
{
((Label)child).Text=String.Empty;
}
}
I am not very familiar with WinForms, but I think there are containers there.
Set the Tag property of the labels you do not want cleared to the string "DoNotClear" (using the Property Window or code) then use the following LINQ code:
foreach (var label in Controls.OfType<Label>().Where(l => l.Tag != "DoNotClear"))
label.Text = string.Empty;
Solution : you can use Controls.Find() method to find the controls from id label50 to label82 and assign String.Empty for each identified Label.
Try This:
private void button1_Click(object sender, EventArgs e)
{
for(int i=50;i<83;i++)
{
this.Controls.Find("label" + i,true)[0].Text = String.Empty;
}
}
If all your labels have names like label + id
var labelsToClear = from l in Controls.OfType<Label>()
let id = Int32.Parse(l.Name.Replace("label", ""))
where id >= 50 && id <= 82
select l;
foreach(var label in labelsToClear)
label.Text = String.Empty;
If labels can have different names, then you can filter out labels which match label + id pattern:
Controls.OfType<Label>().Where(l => Regex.IsMatch(l.Name, #"^(?:label)\d+$"))

Set all Labels Font before opening the Form

Before opening the form I used following code to check if its label then change the font
foreach (Label ctl in frm.Controls)
{
ctl.Font = usefontgrid;
}
But on first line return error because it check other control types such as textbox or button,etc.
How can I check if the object is only label then go to for each?
Try this;
foreach (Control c in this.Controls)
{
if (c is Label)
c.Font = usefontgrid;
}
Or
foreach (var c in this.Controls.OfType<Label>())
{
c.Font = usefontgrid;
}
Its not clear where you place this code (should be after initialize component) but try
foreach (Label ctl in frm.Controls.OfType<Label>())
{
ctl.Font = usefontgrid;
}
There is also the following Linq to do the same thing
foreach (Label ctl in frm.Controls.Where(x => x is Label))
try this.
foreach (Control ctl in frm.Controls)
{
if(ctl.GetType()==typeof(Label)){
ctl.Font = usefontgrid;
}
}
frm.controls will give all controls
You need to check whether the control is a type of Label.

Groupbox foreach not finding all textboxes [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am trying to find which textbox i have entered the information into on a form and make the rest of the textboxes within the form blanked out and locked so no information can be entered into them.
The problem is when i run the code and debug. I do not seem to be finding all the textboxes that are on the form when looping through them.
I have tried to change some of the information in the foreach by trying to find if groupbox name.equals and if items within groupbox equal text. I assume i have made mistake with the foreach statements.
Below is my code.
foreach (Control C in this.Controls)
{
if (C is GroupBox)
foreach (Control T in this.Controls)
{
if (T is TextBox)
{
{
if (T.Text != string.Empty && T.Name.Equals("txtlotno"))
{
txtheads.Enabled = false;
txtheads.BackColor = Color.LightGray;
GroupBoxHeads.BackColor = Color.LightSlateGray;
txtrisersgood.Enabled = false;
txtrisersgood.BackColor = Color.LightGray;
GroupBoxRisers.BackColor = Color.LightSlateGray;
}
else if (T.Text != string.Empty && T.Name.Equals("txtvingot"))
{
txtheads.Enabled = false;
txtheads.BackColor = Color.LightGray;
GroupBoxHeads.BackColor = Color.LightSlateGray;
txtrisersgood.Enabled = false;
txtrisersgood.BackColor = Color.LightGray;
GroupBoxRisers.BackColor = Color.LightSlateGray;
}
else if (T.Text != string.Empty && T.Name.Equals("txtheads"))
{
txtvingot.Enabled = false;
txtvingot.BackColor = Color.LightGray;
txtlotno.Enabled = false;
txtlotno.BackColor = Color.LightGray;
GroupBoxIngot.BackColor = Color.LightSlateGray;
txtrisersgood.Enabled = false;
txtrisersgood.BackColor = Color.LightGray;
GroupBoxRisers.BackColor = Color.LightSlateGray;
}
else if (T.Text != string.Empty && T.Name.Equals("txtrisersgood"))
{
txtvingot.Enabled = false;
txtvingot.BackColor = Color.LightGray;
txtlotno.Enabled = false;
txtlotno.BackColor = Color.LightGray;
GroupBoxHeads.BackColor = Color.LightSlateGray;
txtheads.Enabled = false;
txtheads.BackColor = Color.LightGray;
GroupBoxIngot.BackColor = Color.LightSlateGray;
}
}
}
}
}
There is a simple error in your loop initialization
foreach (Control C in this.Controls)
{
if (C is GroupBox)
{
foreach (Control T in C.Controls)
{
......
The second foreach should work on the controls of the groupbox not again on this.Controls.
Of course, these loops works only for TextBoxes contained in a GroupBox. If you have a TextBox outside of any GroupBox this code will not find them-
However, why do you need a loop?
You change a finite number of textboxes, so you could just access the textboxes directly
if (txtlotno.Text != string.Empty)
{
txtheads.Enabled = false;
txtheads.BackColor = Color.LightGray;
GroupBoxHeads.BackColor = Color.LightSlateGray;
txtrisersgood.Enabled = false;
txtrisersgood.BackColor = Color.LightGray;
GroupBoxRisers.BackColor = Color.LightSlateGray;
}
.... and so on the the other three
Your issue seems to be that you are iterating through this.Controls and not the controls in your groupbox
However, the loop seems redundant, since you directly access each Textbox by name. I would maybe try something like this:
List<TextBox> _disable = new List<TextBox>();
List<TextBox _enable = new List<TextBox>();
// Gather Textboxes to be disabled and enabled
foreach(Control c in this.Controls)
{
GroupBox group = c as GroupBox;
if(group == null ) // Not a group box so continue on
continue;
foreach(Control c in group.Controls)
{
TextBox tb = c as TextBox;
if(tb == null )
continue; // Not a textbox so continue on
if(!String.IsNullOrWhitespace(tb.Text)) // We have information so add to _enable
_enable.Add(tb);
else
_disable.Add(tb); // empty textbox so ... disable
}
}
// Enable or Disable Textboxes
foreach(TextBox tb in _enable)
{
tb.Enabled = true;
tb.BackColor = Colors.White
}
foreach(TextBox tb in _disable)
{
tb.Enabled = false;
tb.BackColor = Colors.LightGrey
}
This approach lets you Loop through all your group boxes, loop through all their textboxes and organize each textbox and enable/disable them together, or not disable any if the _enable list is empty. Alternatively, instead of adding them to a list, you could just disable them/enable them right there.
Hope this helps
It appears that you want to iterate through the Controls of the GroupBox:
foreach (Control C in this.Controls)
{
if (C is GroupBox)
foreach (Control T in C.Controls) // loop GroupBox controls
...
In WPF I am using the following procedure in order to get all TextBox Controls in main Grid and its nested containers. The same approach should work in your case as well.
private List<TextBox> GetTB(Grid Grd)
{
List<TextBox> _lstT = new List<TextBox>();
try
{
// get ALL TextBox in main Grid and sub Grid/UniformGrid
UIElementCollection _mainGrd = Grd.Children;
foreach (UIElement el in _mainGrd)
{
if (el is TextBox) { _lstT.Add((TextBox)el); }
else if (el is Grid)
{
foreach (UIElement el1 in ((Grid)el).Children)
{ if (el1 is TextBox) { _lstT.Add((TextBox)el1); } }
}
else if (el is UniformGrid)
{
foreach (UIElement el1 in ((UniformGrid)el).Children)
{ if (el1 is TextBox) { _lstT.Add((TextBox)el1); } }
}
}
return _lstT;
}
catch { throw; }
}

how can i modify Some controls with similar tags at onec in C#?

I have a VB code here and i wanna convert it into C# format, i'm new in C#. can anybody help me?
here is VB code:
Dim o As Object
For Each o In Me.Controls
If o.tag= "1" Then
o.BackColor = Color.Blue
End If
i want to modify an option in some of my form's controls with tag "1". how can i do that in C#?
That makes rather heavy use of vb.net's support for dynamic typing. Avoid using sample code like that.
foreach (Control ctl in this.Controls) {
if (ctl.Tag.ToString() == "1") {
ctl.BackColor = Color.Blue;
}
}
This will do what you want in C#
foreach (Control o in this.Controls)
{
if (o.Tag.ToString() == "1")
o.BackColor = Color.Blue;
}
for (int i = 0; i < Me.Controls.Count; i++)
{
var o = Me.Controls[i];
if (o.tag == "1")
o.BackColor = Color.Blue;
}

C# - FindControl by ID and modify some properties

I'm creating some checkbox's from codebehind (adding through Panel.Controls.Add()).
My question is: How can i modify the values?
I've already tried creating the control, use the method FindControl and them change some properties but with no sucess.
CheckBox c = new CheckBox();
c.FindControl("CheckBoxP");
c.Checked = true;
Any ideas? Thanks
CheckBox _C = (CheckBox)this.Controls.Find("checkBox1", true).FirstOrDefault();
if (_C != null)
{
_C.Checked = true;
}
replace the 'checkBox1' with the name of the desired control
Try something like this (assuming you're using Windows Forms):
foreach (Control c in this.Controls)
{
if (c.Name == "MyName" && c is CheckBox)
{
((CheckBox)c).Checked = true;
}
}

Categories

Resources