简体   繁体   English

如何在 label 中打印字符串数组元素? c#

[英]how to print a string array elements in a label ? c#

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: 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:表格 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:表格 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]);假设用户选择“meal1”和“meal3”,现在加载表单 2 时,我必须在 label 中看到“meal1”和“meal3”,但我看到的只是用户的最后选择,我试过String.join("\n",names2[i]); but it printed all the array elements I tried labe1.Text += names2[i] + "\n";但它打印了我尝试过的所有数组元素labe1.Text += names2[i] + "\n"; it also prints the last choice for the user.它还为用户打印最后的选择。

thank you...谢谢你...

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.在这些行中,您只是将名称分配给 label1 但每次分配新值时,旧值都会被替换。 You should change this assignment line as您应该将此分配行更改为

if(Form1.names[i].Equals(names2[i])){
         label1.Text += names2[i] + "\n";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM