Reputation: 3
My problem is common which is to print an array elements inside a label in windows form with c# but I wanted to use if statement to print a certain elements not all the elements , the code has two forms :
form 1 :
public static String [] names = new String [3];
private void button (sender and whatever ...){
if(label1.Text.Equals("meal1")){
names[0] = "name1";
}
if(label1.Text.Equals("meal2")){
names[1] = "name2";
}
if(label1.Text.Equals("meal3")){
names[2] = "name3";
}
this.Hide();
Form2 frm2 = new Form2();
frm2.Show();
}
I did this to send the array data to the next form , the elements of the array are stored depending on user choice from a menu
form 2 :
private void Form2_Load(...){
String [] names2 = {"name1" , "name2" , "name3"};
for(int i = 0 ; i < Form1.names.Length ; i++){
if(Form1.names[i].Equals(names2[i])){
label1.Text = names2[i] + "\n";
}
}
}
lets say user chooses "meal1" and "meal3" , now when form 2 is loaded I must see "meal1" and "meal3" in the label but all I see is the last choice of the user , I tried String.join("\n",names2[i]);
but it printed all the array elements I tried labe1.Text += names2[i] + "\n";
it also prints the last choice for the user.
thank you ...
Upvotes: 0
Views: 359
Reputation: 641
Yah, I got your problem. every time you run your code you will get the last name whose condition will be true. Here is solution to your problem.
if(Form1.names[i].Equals(names2[i])){
label1.Text = names2[i] + "\n";
}
In these lines, you are just assigning the name to label1 but every time you assign a new value, the old value is replaced. You should change this assignment line as
if(Form1.names[i].Equals(names2[i])){
label1.Text += names2[i] + "\n";
}
Upvotes: 2