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