I'm trying to create a loop that will change my array of labels to match a list from another class. I declared the list as
private List<string> Status = new List<string>(2);
public List<string> GetList()
{
return Status;
}
private void btnFind_Click(object sender, EventArgs e)
{
Position.Add("Unpaid");
Position.Add("Paid");
Position.Add("Unpaid");
}
And in the second form
public partial class Form2 : Form
{ Label[] Labels = new Label[3];
private void Form2_Load(object sender, EventArgs e)
{
Labels[0] = this.lblTony;
Labels[1] = this.lblSteve;
Labels[2] = this.lblPeter;
Form1 f1 = new Form1 ();
for (int i = 0; i !=3 ; i )
{
List<string> Status = f1.GetList();
Labels[i].Text = Status[i];
}
}
}
'''
I tried to only put the relevant codes but I may be missing something? The error is IndexOutOfRangeException which I do not get because the are the same size. I tried changing the sizes but the error only changes to argumentoutofbounds
CodePudding user response:
try this :
status.Add(lables[i].Text);
insted of
lables[i].Text = status[i];
I Dont Test it But I think its going to work! go forward
CodePudding user response:
There are a lot of things that are not great in the code you have shown but if you want to follow this approach then why not just:
class Form1
{
private List<string> Status = new List<string>();
public List<string> GetList()
{
return Status;
}
// I'm guessing as to how you add elements to Status
public Form1()
{
Status.Add("Item 1");
Status.Add("Item 2");
Status.Add("Item 3");
}
}
public partial class Form2 : Form
{
Label[] Labels = new Label[3];
private void Form2_Load(object sender, EventArgs e)
{
Labels[0] = this.lblTony;
Labels[1] = this.lblSteve;
Labels[2] = this.lblPeter;
Form1 f1 = new Form1();
List<string> Status = f1.GetList();
Debug.Assert(Labels.Length == Status.Count());
for (int i = 0; i < Status.Count(); i)
{
Labels[i].Text = Status[i];
}
}
}
It looks like your main problem is that you have allocated a space of 2 for Status when you construct the object but then run the loop for 3 when copying the values over. If you are using a List you rarely need to pre-allocate its size.
