简体   繁体   中英

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

I just want to add the names of Astrology Stars in Listbox in Xaml Code

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

......

and then i tried by making a list of StarName

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

Every time a run the code ,there is NullReferenceException at following line

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

Further More I will like know,how can i Bind This data Directly to listview in XAML.

Place your code after the call to InitializeComponent() .
That method is responsible for creating the instances of the UI elements. If you try to access them earlier, they are still null , hence the NullReferenceException when trying to access listBox1 .

Furthermore, your code contains some redundant stuff:

  1. Calling ToString() on a string is unnecessary. Remove it.
  2. Creating an array just to create a list from it is unnecessary. You can use a collection initializer instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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