【问题标题】:how to print a string array elements in a label ? c#如何在标签中打印字符串数组元素? C#
【发布时间】:2020-04-09 10:44:06
【问题描述】:

我的问题很常见,即使用 c# 在 windows 窗体的标签内打印数组元素,但我想使用 if 语句打印某些元素而不是所有元素,代码有两种形式:

表格 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 加载时,我必须在标签中看到“meal1”和“meal3”,但我看到的只是用户的最后选择,我试过 @987654323 @ 但它打印了我尝试过的所有数组元素labe1.Text += names2[i] + "\n"; 它还打印了用户的最后选择。

谢谢你...

【问题讨论】:

  • 你需要在这行label1.Text += names2[i] + "\n";使用+=操作符而不是=
  • 打印是,如果你把东西送到打印机。
  • Holger,感谢您提供的信息,也许是因为我主要使用 Java,我们经常使用“打印”这个短语,这个短语有替代品吗?
  • @SalahAkbari,它运作良好,谢谢,但空指针问题出现任何想法?

标签: c# arrays .net


【解决方案1】:

是的,我有你的问题。每次运行代码时,您都会得到条件为真的姓氏。这是您的问题的解决方案。

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

【讨论】:

  • 谢谢它的工作,但出现了另一个问题,即空指针......这里有空指针吗?
  • 越界循环时发生空指针异常。更改您的 for 循环如下: ................................ for(int i = 0 ; i
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
相关资源
最近更新 更多