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;
}
Related
I've currently got 5 labels in a Windows Form on Visual Studio and I need to populate an array with these 5 labels.
The 5 labels are named 'die1', 'die2', 'die3', 'die4', 'die5'
I figured I should be able to generate the array and then use a for loop to populate it, but the for loop is where I get stuck. This is what I have so far:
Label[] labels = new Label[5];
for (int i = 0; i < labels.Length; i++)
labels[i] = new Label(die(i));
Any help would be appreciated!
You can use LINQ to search the collection of controls on the Form, and create an array from any Label's whose name starts with "die":
var labels = Controls.OfType<Label>()
.Where(label => label.Name.StartsWith("die"))
.ToArray();
Label[] lbl ;
private void setupControls()
{
int Totallbl = 5;
int height = 30;
lbl = new Label[Totallbl];
try
{
for (int i = 0; i < Totallbl; i++)
{
lbl[i] = new Label();
lbl[i].Location = new Point(20, ((i + 1) * height));
lbl[i].Name = "lbl" + i;
lbl[i].Text = "LabelText";
lbl[i].AutoSize = true;
this.Controls.Add(lbl[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You can call back the label like this:
lbl[0].Text = "Text u want to change"
lbl[1].Text = "Text u want to change"
...
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;
}
I have list where are 6 sentences which I want to put in 6 different labels.
All six labels are named Slot0Sentence, Slot1Sentence, Slot2Sentence...
This is how I loop
for (int i = 0; i < ls.Count; i++)
{
Slot0Sentence.Text = ls[i];
}
However I dont know how to access other labels.
If there would be normal string I would do Slot + i + Sentence but in this case this dont work.
with an array of labels you can control their properties. you don't need design here, you can do that with code.
Label[] l = new Label[6];
int x = 20;
for (int i = 0; i < l.Length; i++)
{
l[i] = new Label();
l[i].Name = "Hello " + i.ToString();
l[i].Text = "Hello " + i.ToString();
l[i].Location = new Point(x, 10);
x += 100;
}
you can change the names and text to whatever you like.
I'd just use Children property of parent container (Grid, StackPanel,..). This gives you a collection which supports indexes. Additionally, in case you have different controls, use if statement
if(element in Label)
{
element.Text = ...
}
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;
}