I have nine labels with the names "lbl101", "lbl102", ...
I want to do this:
for (int i = 0; i < 9; i++)
{
sting name = "lbl10" + i;
name.BackColor = Color.Red;
}
How can I do this?
You can add the controls to a collection, and loop through that.
var labels = new List<Label> { lbl101, lbl102, lbl103 };
foreach (var label in labels)
{
label.BackColor = Color.Red;
}
Alternatively, if you just want every Label on the Form that starts with "lbl10", you can use LINQ to query the collection of controls:
var labels = this.Controls.OfType<Label>()
.Where(c => c.Name.StartsWith("lbl10"))
.ToList();
If labels are set on the form, you can use Linq:
var labels = Controls // or MyPanel.Controls etc. if labels are on panel
.OfType<Label>()
.Where(label => label.Name.StartsWith("lbl10"));
foreach (var label in labels)
label.BackColor = Color.Red;
Loop through the container they are in and grab a reference to them.
for(int i = 0; i<9; i++)
{
var label = (Label)yourForm.FindControl("lbl10" + i.ToString());
label.BackColor = Color.Red;
}
Probably the simplest thing would be to list them all out:
lbl100.BackColor = Color.Red;
lbl101.BackColor = Color.Red;
lbl102.BackColor = Color.Red;
lbl103.BackColor = Color.Red;
lbl104.BackColor = Color.Red;
lbl105.BackColor = Color.Red;
lbl106.BackColor = Color.Red;
lbl107.BackColor = Color.Red;
lbl108.BackColor = Color.Red;
This is the most straightforward way to do it. If you really want to be fancy, you could put them all in an array and iterate over that:
Label[] labels = new Label[]{
lbl100, lbl101, lbl102, lbl103, lbl104, lbl105, lbl106, lbl107, lbl108
};
for (int i = 0; i < labels.Length; i++)
{
labels[i].BackColor = Color.Red;
}
Or, if you know that all the labels are children of a certain control and there are no other labels in that control, you could do this:
foreach (Control c in someControl.Controls)
{
if (c is Label)
{
((Label)c).BackColor = Color.Red;
}
}
public void changebackground()
{
Label mylabel;
foreach (Control con in this.Controls)
{
if (con.GetType() == typeof (Label)) //or any other logic
{
mylabel = (Label)con;
mylabel.BackColor = Color.Red;
}
}
}
In Windows Form, to point to a control, just call it with the following sentence
this.Controls[control name]
for example
this.Controls["label1"].BackColor = Color.Blue;
So the answer to your question
for (int i = 0; i < 9; i++)
{
this.Controls["lbl10" + i.ToString()].BackColor = Color.Red;
}
Related
I'm trying to turn textboxes and buttons visible when the number of tracks it's selected in a combobox.
For example: when I select 3, just 3 textboxes and the 3 respective buttons to select the tracks are enabled. How can I change this code that I've made to a simple foreach or a for?
if (numero_faixas == 1) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
} else if (numero_faixas == 2) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
} else if (numero_faixas == 3) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
txtFaixa3.Visible = true;
btnFaixa3.Visible = true;
}
You can reduce the lines of code by changing your conditions, so you don't have to reference the same control so many times:
if (numero_faixas > 0)
{
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
}
if (numero_faixas > 1)
{
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
}
if (numero_faixas > 2)
{
txtFaixa3.Visible = true;
btnFaixa3.Visible = true;
}
To use a foreach loop, you could cast the Controls collection to an IEnumerable<Control> and then, using System.Linq;, you can filter on controls of type TextBox and Button, where the control name contains "Faxia". Then, in the loop body, we can use int.TryParse to try to convert the last character of the control name to an int, and if that succeeds, then set the control to Visible if the control number is less than numero_faixas + 1:
foreach (Control control in Controls.Cast<Control>()
.Where(c => (c is Button || c is TextBox) && c.Name.Contains("Faixa")))
{
// Get the number associated with this control and compare it to numero_faixas
int controlNumber;
if (int.TryParse(control.Name.Substring(control.Name.Length - 1), out controlNumber) &&
controlNumber < numero_faixas + 1)
{
control.Visible = true;
}
}
Here's a proof of concept that you could respin using your business rules.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ShowHideButtons_47439046
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitOurThings();
}
private void InitOurThings()
{
//lets create a combo box with options to select
ComboBox combo = new ComboBox();
combo.Location = new Point(5, 5);//place it somewhere
//add selectable items
for (int i = 0; i < 10; i++)
{
combo.Items.Add(i);
}
combo.SelectedValueChanged += Combo_SelectedValueChanged;//the event which will handle the showing/hidding
Controls.Add(combo);//add the combo box to the form
//lets create some buttons and textboxes
int btnx = 5;
int btny = combo.Height + combo.Location.Y + 5;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Location = new Point(btnx, btny);
btn.Name = i.ToString();
btn.Text = i.ToString();
Controls.Add(btn);
btny += btn.Height + 5;
TextBox txtbx = new TextBox();
txtbx.Location = new Point(btn.Location.X + btn.Width + 5, btn.Location.Y);
txtbx.Name = i.ToString();
txtbx.Text = i.ToString();
Controls.Add(txtbx);
}
}
private void Combo_SelectedValueChanged(object sender, EventArgs e)
{
int selectedValue = int.Parse(((ComboBox)sender).SelectedItem.ToString());
foreach (Control item in Controls)
{
//show/hide the controls based on their Name being Equal Or Smaller than the selectedItem
if (item is TextBox)
{
int itemNumber = int.Parse(item.Name);
item.Visible = itemNumber <= selectedValue ? true : false;
}
if (item is Button)
{
int itemNumber = int.Parse(item.Name);
item.Visible = itemNumber <= selectedValue ? true : false;
}
}
}
}
}
Suppose I have this in page load:
Label lblc = new Label();
for (int i = 1; i <= 10; i++)
{
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
How can I manipulate each of these controls at run time?
I want to:
Set/get their text.
Reference a particular control, in this case Label.
Use an array if you know how many labels you will have,
Label[] lblc = new Label[10];
for (int i = 0; i < 10; i++)
{
lblc[i] = new Label() { Text = (i + 1).ToString() };
this.Controls.Add(lblc[i]);
}
Then you will reference the textbox 1 with lblc[0] and textbox 2 with lblc[1] and so on. Alternatively if you do not know how many labels you will have you can always use something like this.
List<Label> lblc = new List<Label>();
for (int i = 0; i < 10; i++)
{
lblc.Add(new Label() { Text = (i + 1).ToString() });
this.Controls.Add(lblc[i]);
}
You reference it the same way as the array just make sure you declare the List or the array outside your method so you have scope throughout your program.
Suppose you want to do TextBoxes as well as Labels well then to track all your controls you can do it through the same list, take this example where each Label has its own pet TextBox
List<Control> controlList = new List<Control>();
for (int i = 0; i < 10; i++)
{
control.Add(new Label() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
control.Add(new TextBox() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
}
Good luck! Anything else that needs to be added just ask.
Your code creates only one control. Because, label object creation is in outside the loop. you can use like follows,
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Text = i.ToString();
lblc.Name = "Test" + i.ToString(); //Name used to differentiate the control from others.
this.Controls.Add(lblc);
}
//To Enumerate added controls
foreach(Label lbl in this.Controls.OfType<Label>())
{
.....
.....
}
Better to set the Name and then use that to distinguese between the controls
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Name = "lbl_"+i.ToString();
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
when:
public void SetTextOnControlName(string name, string newText)
{
var ctrl = Controls.First(c => c.Name == name);
ctrl.Text = newTExt;
}
Usage:
SetTextOnControlName("lbl_2", "yeah :D new text is awsome");
I have ten labels on a page. I want to make these invisible in a for loop on page load.
I have tried this (doesn't work):
for (int i = 0; i < 10; i++)
{
my_lbl+i.Visible = false;
}
Therefore, it should do:
my_lbl1.Visible = false;
my_lbl2.Visible = false;
my_lbl3.Visible = false;
my_lbl4.Visible = false;
etc...
Is there a way to do this?
Put all of the labels into a collection:
private List<Label> labels = new List<Label>{my_lbl1, my_lbl2, my_lbl3, my_lbl4};
Then you can iterate the whole collection:
foreach(var label in labels)
label.Visible = false;
Make a List of them;
List<Label> yourlabels = new List<Label>{my_lbl1, my_lbl2, my_lbl3...};
and use foreach loop making them visible.
foreach(var label in yourlabels)
{
label.Visible = false;
}
I don't know if there is a better way but this way seems logical to me.
Putting the labels in a collection (as the previous answers have suggested) is a great solution. You can also retrieve the controls by their name using FindControl method of the Page.
for (int i = 0; i < 10; i++)
{
this.FindControl("my_lbl" + i.ToString()).Visible = false;
}
I guess you can utillize Page's FindControl method:
for (int i = 0; i < 10; i++)
{
FindControl(string.Format("my_lbl{0}", i)).Visible = false;
}
But check the case if control is not found of course.
Or, you can put them into dictionary:
Dictionary<string, Label> nameOfDict = new Dictionary<string, Label>();
nameOfDict.Add("label1", label1);
nameOfDict.Add("label2", label2);
For...
nameOfDict ["label" + incrementator].visible = false;
Or, create them dynamically into an array of labels.
If you're sure that, let's say, you want to uncheck all checkboxes in a groupbox, you can do this, too:
foreach (var item in groupBox1.Controls)
{
if (item.GetType() == typeof(CheckBox))
{
((CheckBox)item).Checked = true;
}
}
with LINQ:
foreach (var item in groupBox1.Controls.Cast<object>().Where(item => item.GetType() == typeof(CheckBox)))
{
((CheckBox)item).Checked = true;
}
I have 10 RadioButton inside a panel.
I have 10 panels inside a tableLayoutPanel, Each one in different column.
How can i move between the columns and validate that in each column there is a selected radioButton?
Thank you.
I have no experiences with the TableLayoutPanel, but you could try this:
bool allValid = true;
for(int c = 0; c < panel.ColumnCount; c++)
{
var colRadios = panel.Controls.OfType<RadioButton>()
.Where(rb => panel.GetColumn(rb) == c);
bool colValid = colRadios.Any(rb => rb.Checked);
if(!colValid)
{
allValid = false;
break;
}
}
(panel is the TableLayoutPanel)
I have a simple for loop as follows:
for (int i = 0; i > 20; i++)
{
}
Now I have 20 labels (label1, label2, label3 and so on..)
I would like to do something like:
for (int i = 0; i > 20; i++)
{
label[i].Text = String.Empty;
}
What is the easiest way to accomplish this?
If your labels are placed on one container, say Form, you may do the following:
foreach(Label l in this.Controls.OfType<Label>())
{
l.Text = string.Empty;
}
Same for any other container, say, Panel or GroupBox, just replace this with the name of the container (panel1.Controls, etc.)
I'd call your solution a design-flaw, but I'd go for something like this:
var itemArray = this.Controls.OfType<Label>();
foreach(var item in itemArray)
{
item.Text = string.Empty;
}
Create an array or list of labels and loop through that list to set the properties of each label
List<Label> labels = new List<Label>();
labels.Add(label1);
foreach(Label l in labels)
{
l.Text = String.Empty;
}
Don't know if its the easiest, it is the shortest though..
this.Controls.OfType<Label>().ToList().ForEach(lbl => { lbl.Text = String.Empty; });
Maybe you can use FindControl with something like
for(int i = 0; i < 5; i++)
{
(FindControl("txt" + i.ToString())).Text = String.Emty;
}