Adding i value to control name - c#

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;
}

Related

How to reverse a FlowLayoutPanel?

I'm trying to reverse the order of Controls in a FlowLayoutPanel.
I tried converting the ControlCollection to an array and then reversed that and cleared the ControlCollection and then readded the Controls. But this doesn't seem to have the planned effect.
Here's the code I use:
private static void ReverseLayout(Control control, bool suspend = true) {
if (suspend) control.SuspendLayout();
Control[] newCC = new Control[control.Controls.Count];
control.Controls.CopyTo(newCC, 0);
Array.Reverse(newCC);
control.Controls.Clear();
//control.Controls.AddRange(newCC);
for (int i = 0; i < newCC.Length; i++) {
newCC[i].Location = new System.Drawing.Point(); // maybe? no :\
newCC[i].TabIndex = i; // maybe? no :\
control.Controls.Add(newCC[i]);
}
if (suspend) control.ResumeLayout(false);
}
Your code seems more complicated than it needs to be. Try putting the controls in a List<Control> and then call reverse on it, put the collection back:
int firstTabIndex = flp.Controls[0].TabIndex;
List<Control> controls = flp.Controls.Cast<Control>().ToList();
flp.Controls.Clear();
controls.Reverse();
flp.Controls.AddRange(controls.ToArray());
For the TabIndex property, you would have to reapply the value:
for (int i = 0; i < flp.Controls.Count; ++i) {
flp.Controls[i].TabIndex = firstTabIndex + i;
}

Looping through labels in C#

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;
}

Using for loop with an object name

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;
}

How to write a list of array in a for loop?

Hi I neeed to do this one in a loop, but I don't have any idea how to do. I can't do this by just simply incrementing it.
CheckBox[] checkboxarray;
checkboxarray = new CheckBox[] {
txtChckBx0, txtChckBx1, txtChckBx2, txtChckBx3, txtChckBx4, txtChckBx5,
txtChckBx6, txtChckBx7, txtChckBx8, txtChckBx9, txtChckBx10, txtChckBx11,
txtChckBx12, txtChckBx13, txtChckBx14, txtChckBx15, txtChckBx16, txtChckBx17,
txtChckBx18, txtChckBx19, txtChckBx20, txtChckBx21, txtChckBx22, txtChckBx23,
txtChckBx24, txtChckBx25, txtChckBx26, txtChckBx27, txtChckBx28, txtChckBx29,
txtChckBx30, txtChckBx31, txtChckBx32, txtChckBx33, txtChckBx34, txtChckBx35,
txtChckBx36, txtChckBx37, txtChckBx38, txtChckBx39, txtChckBx40, txtChckBx41,
txtChckBx42, txtChckBx43, txtChckBx44, txtChckBx45, txtChckBx46, txtChckBx47,
txtChckBx48, txtChckBx49, txtChckBx50, txtChckBx51, txtChckBx52, txtChckBx53,
txtChckBx54, txtChckBx55, txtChckBx56, txtChckBx57, txtChckBx58, txtChckBx59,
txtChckBx60, txtChckBx61, txtChckBx62, txtChckBx63, txtChckBx64, txtChckBx65,
txtChckBx66, txtChckBx67, txtChckBx68, txtChckBx69, txtChckBx70, txtChckBx71,
txtChckBx72, txtChckBx73, txtChckBx74, txtChckBx75, txtChckBx76, txtChckBx77,
txtChckBx78, txtChckBx79, txtChckBx80
};
If you know that the checkboxes are all on a form:
var list = new List<CheckBox>();
foreach(var control in this.Controls)
{
var checkBox = control as CheckBox;
if(checkBox != null)
{
list.Add(checkBox);
}
}
var checkBoxArray = list.ToArray();
If you don't know where the controls are then you will have to search for them.
BTW: The code above uses WinForms. If you are using WPF, Silverlight, Metro,... the container will be named differently.
You can't do new and then
checkboxarray = new CheckBox[] { txtChckBx0, ....}
it's two different ways to define an array.
you need to do:
CheckBox[] checkboxarray = { txtChckBx0, ....};
If you want it to work.
Good luck.
In WinForm
List<CheckBox> checkBox = new List<CheckBox>();
// Adding checkboxes for testing...
for (int i = 0; i <= 80; i++)
{
var cbox = new CheckBox();
cbox.Name = "txtChckBx"+ i.ToString();
checkBox.Add(cbox);
Controls.Add(cbox);
}
List<CheckBox> checkBoxfound = new List<CheckBox>();
// loop though all the controls
foreach (var item in Controls)
{
// filter for checkboxes and name should start with "txtChckBx"
if (item is CheckBox && ((CheckBox)item).Name.StartsWith("txtChckBx", StringComparison.OrdinalIgnoreCase))
{
checkBoxfound.Add((CheckBox)item);
}
}

How can I unselect item in ListView?

I have a ListView with a couple of items in it. When the ListView looses focus, the last selected ListViewItem is still "selected" with a gray background.
I would like to achieve that on ListView.FocusLost, the selection is gone and therefore the ListView.SelectedIndexChanged event will occur.
Any ideas?
I am using .NET CF 3.5.
Suppose you are accessing the ListView from a parent form/control.
You can add this piece of code in the form's/control's constructor/load event:
this.myListView.LostFocus += (s, e) => this.myListView.SelectedIndices.Clear();
Ok, so in your case, you would replace that delegate with:
if (this.myListView.SelectedIndices.Count > 0)
for (int i = 0; i < this.myListView.SelectedIndices.Count; i++)
{
this.myListView.Items[this.myListView.SelectedIndices[i]].Selected = false;
}
You can give the code a nicer form, btw.
myListView.SelectedItems.Clear();
I know this is late but in case someone else needed the solution I would like to add to the solution.
You need to set the Focused property to false to avoid deselected items having focus.
for (int i = 0; i < this.myListView.SelectedIndices.Count; i++)
{
this.myListView.Items[this.myListView.SelectedIndices[i]].Selected = false;
this.myListView.Items[this.myListView.SelectedIndices[i]].Focused = false;
}
This is easier.
this.myListView.SelectedIndex = -1;
this.myListView.Update();
Another effective way to approach this would be:
foreach (ListViewItem i in myListView.SelectedItems)
{
i.Selected = false;
}
You can try it:
MyList.ItemSelected += (sender, e) => {
((ListView)sender).SelectedItem = null;
};
or if you have the OnSelection created in your View code behind(xaml.cs):
private void OnSelection(object sender, SelectedItemChangedEventArgs e)
{
((ListView)sender).SelectedItem = null;
}
Regards
If you are using EditItemTemplate, rather than ItemTemplate, you may have been trying to figure out why ListView1.SelectedIndex = -1; hasn't been working. It's because you need to use ListView1.EditIndex = -1;
if (listView1.SelectedItems.Count > 0)
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
listView1.SelectedItems[i].Selected = false;
}

Categories

Resources