繁体   English   中英

通过C#中的数组或列表在列表框中添加值时发生Nullrefererencepointer异常

[英]Nullrefererencepointer Exception when adding values in list box through Array or List in c#

我只想在Xaml代码的Listbox框中添加占星术的名称

public MainPage()
    {
    string[] StarsName = {"Aries","Taurus","Aquarius","Pisces"};

        List<string> Stars = new List<string>(StarsName);

        foreach (string abc in StarsName)
        {
            listBox1.Items.Add(abc.ToString());
        }
    }

......

然后我尝试列出StarName

                  foreach (string abc in Stars)
                 {
                   listBox1.Items.Add(abc.ToString());
                 }

每次运行该代码时,以下行都会存在NullReferenceException

                 listBox1.Items.Add(abc.ToString());

更多信息我想知道,我该如何将该数据直接绑定到XAML中的listview。

将代码放在对InitializeComponent()的调用之后
该方法负责创建UI元素的实例。 如果您尝试更早地访问它们,则它们仍然为null ,因此在尝试访问listBox1时会出现NullReferenceException

此外,您的代码包含一些多余的东西:

  1. 不需要在string上调用ToString() 去掉它。
  2. 创建数组只是为了从中创建列表是不必要的。 您可以改为使用集合初始化程序。

暂无
暂无

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

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