簡體   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:

表格 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();
}

我這樣做是為了將數組數據發送到下一個表單,數組元素的存儲取決於用戶從菜單中的選擇

表格 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";
        }
    }

}

假設用戶選擇“meal1”和“meal3”,現在加載表單 2 時,我必須在 label 中看到“meal1”和“meal3”,但我看到的只是用戶的最后選擇,我試過String.join("\n",names2[i]); 但它打印了我嘗試過的所有數組元素labe1.Text += names2[i] + "\n"; 它還為用戶打印最后的選擇。

謝謝你...

是的,我有你的問題。 每次運行代碼時,您都會得到條件為真的姓氏。 這是您的問題的解決方案。

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

在這些行中,您只是將名稱分配給 label1 但每次分配新值時,舊值都會被替換。 您應該將此分配行更改為

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