Fill an array with a loop - c#

I want to get a shorter code than now but I don't know how.
What I do now is like the code below.
arrPictureBox[0] = picChair0;
arrPictureBox[1] = picChair1;
arrPictureBox[2] = picChair2;
arrPictureBox[3] = picChair3;
arrPictureBox[4] = picChair4;
arrPictureBox[5] = picChair5;
arrPictureBox[6] = picChair6;
arrPictureBox[7] = picChair7;
arrPictureBox[8] = picChair8;
arrPictureBox[9] = picChair9;
arrPictureBox[10] = picChair10;
arrPictureBox[11] = picChair11;
(pic) is a picturebox.
But I want less code but I don't know if it possible to do this with a loop (for loop).
for (int i = 0 ; i < arrPictureBox.Length; i++)
{
arrPictureBox[i] = picChair + i;
}

If picChairN is a local variable then there's nothing you can do to simplify it as much as you'd like. The best you can do is
arrPictureBox = new [] { picChair0, picChair1, picChair2, picChair3,
picChair4, picChair5, picChair6, picChair7,
picChair8, picChair9, picChair10, picChair11};
If picChairN is a class member (e.g. a field created by the designer) then you could use reflection, but considering you already have the array method typed out I don't see much benefit.

Let's predict you're on WinForms and the pictureBoxes already exist, then you can use the following:
for (int i = 0; i < arrPictureBox.Length; i++)
{
arrPictureBox[i] = this.Controls["picChair" + i];
}
Which actually does this:
get the first Control (a PictureBox for example) with the given name
add the found control to the array of pictureboxes
EDIT:
It might be useful to check for non existing pictureBoxes:
for (int i = 0 ; i < arrPictureBox.Length; i++)
{
var pb = this.Controls["picChair" + i] as PictureBox;
if (pb != null)
{
arrPictureBox[i] = pb;
}
}

You can use al List like below.
List<string> arrPictureBox = new List<string>();
for (int i = 0; i < 20; i++)
{
arrPictureBox.Add("picChair" + i);
}
var result = arrPictureBox.ToArray();
Hope it helps.

If all the picture boxes are on the same form and are the ONLY picture boxes on the form, you can loop through them with something like the following:
int x = 0;
foreach(Control c in this.Controls)
{
if(c is PictureBox)
{
arrPictureBox[x++] = c
}
}

Related

How to change which array I want to modify in a loop without having to type each of them

So I want to change many arrays in a similar way but I'm wondering if instead of doing something like this
for (int i = 0; i < 4; i++)
{
if(i==0)
{
attack1[0] = attacks[i];
attack1[1] = Convert.ToString(atdmg[i]);
attack1[2] = ateffect[i];
attack1[3] = Convert.ToString(ataccur[i]);
attack1[4] = Convert.ToString(atmul[i]);
}
if (i == 1)
{
attack2[0] = attacks[i];
attack2[1] = Convert.ToString(atdmg[i]);
attack2[2] = ateffect[i];
attack2[3] = Convert.ToString(ataccur[i]);
attack2[4] = Convert.ToString(atmul[i]);
}
if (i == 2)
{
attack3[0] = attacks[i];
attack3[1] = Convert.ToString(atdmg[i]);
attack3[2] = ateffect[i];
attack3[3] = Convert.ToString(ataccur[i]);
attack3[4] = Convert.ToString(atmul[i]);
}
if (i == 3)
{
attack4[0] = attacks[i];
attack4[1] = Convert.ToString(atdmg[i]);
attack4[2] = ateffect[i];
attack4[3] = Convert.ToString(ataccur[i]);
attack4[4] = Convert.ToString(atmul[i]);
}
}
I could do something like this
for (int i = 0; i < 4; i++)
{
attacki[0] = attacks[i];
attacki[1] = Convert.ToString(atdmg[i]);
attacki[2] = ateffect[i];
attacki[3] = Convert.ToString(ataccur[i]);
attacki[4] = Convert.ToString(atmul[i]);
}
so that I don't have to type each one. The point of the code is to put information from other arrays into other arrays to simplify printing information in the long run
I don’t think that you really need a loop here. You can simply write like this.
attack1[0] = attacks[0];
attack1[1] = Convert.ToString(atdmg[0]);
attack1[2] = ateffect[0];
attack1[3] = Convert.ToString(ataccur[0]);
attack1[4] = Convert.ToString(atmul[0]);
And similarly for other items.
You can also wrap these lines in a method and call the method based by passing the respective attack object.
As far as I know you cannot change a variable's name like
attacki
A suggestion could be creating a function to do the job inside the loop.
This function could take the array, i, and the other necessary data.
for(int i=0; i<4; ++i)
{
if(i==0)
doSomething(attack1, i, ...)
else if(i==1)
...
}
and then
public void doSomething(array, no, ...)
{
do your stuff here
}
EDIT: You don't really need a loop either anyway. You can just do:
doSomething(attack1, 0, ...)
doSomething(attack2, 1, ...)
doSomething(attack3, 2, ...)
doSomething(attack4, 3, ...)
Perhaps you should package your attack{i} Arrays into a list. Then you could use a foreach loop to update all of them achieving something similar to what you asked for. The code would look something like this:
// Your arrays goes in this
var attackList = new List<string[]>();
int index = 0;
foreach (var attack in attackList)
{
attack[0] = attacks[index];
attack[1] = Convert.ToString(atdmg[index]);
attack[2] = ateffect[index];
attack[3] = Convert.ToString(ataccur[index]);
attack[4] = Convert.ToString(atmul[index);
index++;
}

Checkbox name with For counter

I have this loop and multiple leds. The names of the leds are Led0, Led1, Led2 etc
Now i want to change the background of each Led with this loop so i use the counter iTeller.
I use WPF and only work in the mainwindow.
for (int iTeller = 0; iTeller < bits.Count(); iTeller++)
{
if (bits[iTeller] == 1)
{
//this doesn't work
*Led+iTeller+.Background = Brushes.Green;*
}
}
Try Like This (WPF)
for (int iTeller = 0; iTeller < bits.Count(); iTeller++)
{
if (bits[iTeller] == 1)
{
object i = this.FindName("Led" & iTeller);
if (i is CheckBox)
{
CheckBox k = (CheckBox)i;
MessageBox.Show(k.Name);
}
}
}
This will not work for a lot of reasons. The first is, that your leds are some type of control, which you need in a variable, you cannot simply call them like this.
Do you use WPF or Winforms?
You need a list of your leds, then you can iterate over the list and assign the value to each led
You cannot resolve a variable name like this, you can use the Find method (at least in Windows Forms), to find a named control.
You can also store the controls in an array, that way you prevent using relatively slow Find calls and other error checking:
var leds = new CheckBox[] { Led0, Led1, Led2, Led3, Led4, Led5, Led6, Led7 };
for (int iTeller = 0; iTeller < bits.Count(); iTeller++)
{
if (bits[iTeller] == 1)
{
leds[iTeller].Background = Brushes.Green;
}
}
This worked
for (int iTeller = 0; iTeller < bits.Count(); iTeller++)
{
if (bits[iTeller] == 1)
{
var myCheckbox = (CheckBox)this.FindName("Led" + iTeller);
myCheckbox.Background = Brushes.Green;
}
}
Thanks everyone

Reference a sequence of labels in C#

I have message box that asks the user whether they want to restart.
if (MessageBox.Show("Restart?",
"Restart and Clear",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
labels.Text="0"
}
Instead of "labels" I want to use label1, label2, label3, etc. all the way to label60. I could do label1.Text=label2.Text .... = 0 but that would take a while. Is there an easy way to do this, possibly using a for statement?
I believe what you are trying to do is reset every label's text to 0 if so
foreach(Label l in this.Controls.OfType<Label>())
l.Text = "0";
On a side note, you should try to give your controls meaningful names to help when maintaining your code
Edit
A more robust approach but to make sure you don't reset text that you don't wish to change you could make a subclass of label and then use this class for labels that can be reset
class ResettableLabel : Label
foreach(ResettableLabel l in this.Controls.OfType<ResettableLabel >())...
I'd say you could use Control.ControlCollection.Find
for (int i = 1; i <= 60; i++)
{
label = Controls.Find("label" + i.ToString()) as Label;
label.Text="0"
}
Not tested but I think this Linq version should do the same
Enumerable
.Range(1, 60)
.ToList()
.ForEach(i => (Controls.Find("label" + i.ToString()) as Label).Text = "0");
You could add all of your labels to a collection or a list. Then you could easily ForEach the list.
var allLabels = new List<Label>( { label1, label2, label3, ... , label60});
allLabels.ForEach(l=> l.Text = "0");
Yes, you could use reflection like this:
for (int i = 1; i <= 60; i++)
{
var fi = this.GetType().GetField(string.Format("label{0}", i));
if (fi == null) { continue; }
fi.SetValue(this, "0");
}
Another approach would be to use the Find method:
for (int i = 1; i <= 60; i++)
{
var c = this.Controls.Find(string.Format("label{0}", i), true);
if (c == null) { continue; }
((Label)c).Text = "0";
}
In short, there are a lot of ways to skin this cat. Out of the two I provided, the second is going to be more efficient and would probably be my choice.
Use reflection:
// using System.Reflection;
for (int i = 1; i <= 60; i++)
((Label)this.GetType().GetField("label" + i, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this)).Text = "0";

ASP.NET gives multiple control ID error for one control

I want to add a control to a placeholder dynamically, like this:
int fileCount = Convert.ToInt32(lblCount.Text);
for (int i = 0; i<fileCount ; i++)
{
FileUpload fu = new FileUpload();
if(PlaceHolder1.HasControls())
PlaceHolder1.Controls.AddAt(i,fu);
else
PlaceHolder1.Controls.Add(fu);
PlaceHolder1.Controls[i].ID = "123456abcdef" + i;
}
But I get the error
Multiple controls with the same ID '123456abcdef0' were found. FindControl requires that controls have unique IDs.
Why? Only one control should get that ID on each iteration of the loop.
EDIT: Should mention that I haven't actually been able to test the loop, I get the error even when fileCount is 1.
SOLUTION: I called this function from a "foreach" loop in page load when I thought it was outside of it. Still, having the clear() method in mind will remove the necessity of the addat part of the function.
Just do a clear before you start adding:
PlaceHolder1.Controls.Clear();
And your add statements can be simplified as follows:
FileUpload fu = new FileUpload();
fu.Id = "123456abcdef" + i;
PlaceHolder1.Controls.Add(fu);
As per my knowledge, you can try something like below.
int fileCount = Convert.ToInt32(lblCount.Text);
for (int i = 0; i<fileCount ; i++)
{
FileUpload fu = new FileUpload();
fu.ID = "123456abcdef" + i;
PlaceHolder1.Controls.Add(fu);
}
Hope this Helps!!
Change to this:
int fileCount = Convert.ToInt32(lblCount.Text);
for (int i = 0; i<fileCount ; i++)
{
FileUpload fu = new FileUpload();
fu.ID = string.Format("fu_{0}", i);
PlaceHolder1.Controls.Add(fu);
}

Concatenate strings to make Picturebox name

i have lot of pictureboxes named this way: PBr1_1, PBr1_2, ... PBr1_9
I'd like to make loop
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1"){ "PBr1_"+"i".Tag = "cb.png";}
}
so for i=0 => PBr1_0, i=10 => Pbr1_10.
Example i have value in textbox: 0001011101 - then if value in textbox is "1" then i'd like to change picturebox tag.
How to automate this process, using for example loop "for"?
I suppose your controls are on a WinForm (this) and the ones with that name are all pictureboxes.
If so, that's the way ----
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1")
{
Control[] c = this.Controls.Find("PBr1_" + i.ToString(), true);
if(c != null && c.Length > 0) c[0].Tag = "cb.png";
}
}
You can put the picture boxes in to a List<PicutreBox> and iterate over the list.
var pictures = new List<PictureBox>();
pictures.Add(pic1);
pictures.Add(pic2);
//...
for (int i = 0; i < 10; i++)
{
if (Textbox.Text[i].ToString() == "1")
pictures[i].Tag = "cb.png";
}
Dynamic variable names as in your example are not supported.
Create an array (or list) that contain the picture boxes and use those within the for loop.
You can also use reflection but in my opinion it is best not to use that in this case.
If you are using WinForm you can use Control.Find method to locate a control by name
Once you have got the control you can easily change any property

Categories