-1

I want to add the items from the list box into a string array

However, when I run the code I get a Null Reference Exception on the variable declaration. Any ideas?

List items; string[] array;

    public MainWindow()
    {
        InitializeComponent();

        items = new List<String>();
        listBox.Items.Add("Kevin");
        listBox.Items.Add("James");
        listBox.Items.Add("John");
        listBox.Items.Add("Mathew");
        listBox.Items.Add("George");
Daniel Xi
  • 11
  • 4

1 Answers1

0

You need to initialise the array, you have only declared it as a member of the class:

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    array = new string[listbox.Items.Count];

    ExchangeSort(array);
    listBox.Items.Clear();
    foreach (string i in array)
    {
        listBox.Items.Add(i);
    }
    MessageBox.Show("Done");

}
Matt
  • 2,984
  • 1
  • 24
  • 31
  • I get the error message: Error 1 'System.Windows.Controls.ItemCollection' does not contain a definition for 'Length' and no extension method 'Length' accepting a first argument of type 'System.Windows.Controls.ItemCollection' could be found (are you missing a using directive or an assembly reference?) – Daniel Xi Apr 08 '13 at 03:41
  • Sorry, it's Count, not Length – Matt Apr 08 '13 at 03:56