Question

I have spend the good part of today trying to work out why I am getting this exception. I have a Listbox that is bound to a List in my application. Here is the code:

XAML:

    <ListBox x:Name="SavePanel"
                     ItemsSource="{Binding}"
                     Background="{StaticResource PhoneBackgroundBrush}" Visibility="Visible" SelectionChanged="SavePanel_SelectionChanged" >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Margin="20,5,5,5" Text="{Binding}" FontSize="43"></TextBlock>
                    </DataTemplate>
                </ListBox.ItemTemplate>
    </ListBox>

C#:

List<string> saveNames;

public SaveProject()
{

    InitializeComponent();

    populateList();

    SavePanel.DataContext = saveNames;
}


private void populateList()
{
    if (settings.Contains("saveNames")) //if there are previous saves, pull the names from localstorage
    {
        string test = settings["saveNames"] as string;
        string[] tempArray = test.Split(',');
        totalSaves = tempArray.Length;
        saveNames.Clear(); // clear list
        for (int i = 0; i < totalSaves; i++)
        {
            saveNames.Add(tempArray[i]); // populate list   
        }        
    }
}

Just a quick explanation of "populateList": if "saveNames" exists in localstorage (a list of names separated by commas) the function will split it into an array and then add each name to the List, which in turn goes into the ListBox. This works fine.

I also have no problems displaying, adding, or deleting items from the list. The problem is updating it in the ListBox; want to delete an item from the List "saveNames", and then update the ListBox with the new values. I currently have a button on the application bar that is supposed to do this. I've removed all other code from the event and narrowed it down to simply attempting to nullify the ListBox, and then add the data context again without making any changes; I figured this will work and I can move up from there to find out where I am going wrong in my code. So here is the code for the application bar event now:

private void DeleteProject_Click(object sender, EventArgs e)
{

    SavePanel.DataContext = null;
    SavePanel.DataContext = saveNames;

}

I run my code, everything works until I hit the "delete" button. VS breaks and I get:

A first chance exception of type 'System.NullReferenceException'

This has me stumped; Im not even making changes to the List! It's clear the exception is because of the SavePanel.DataContext = null line. I just have no clue what I am doing wrong here.

Any help would be greatly appreciated!

private void SavePanel_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

    var lb = (sender as ListBox);
    theFileName = lb.SelectedItem.ToString();

    // repopulate appbar to show delete and save buttons
    for (int i = ApplicationBar.Buttons.Count - 1; i >= 0; i--)
    {
        ApplicationBar.Buttons.RemoveAt(i);
    }

    if (totalSaves < 10)
    {
        ApplicationBarIconButton button1 = new ApplicationBarIconButton();
        button1.IconUri = new Uri("/Assets/Icons/add.png", UriKind.Relative);
        button1.Text = "Add";
        ApplicationBar.Buttons.Add(button1);
        button1.Click += new EventHandler(AddProject_Click);
    }

    ApplicationBarIconButton button2 = new ApplicationBarIconButton();
    button2.IconUri = new Uri("/Assets/Icons/delete.png", UriKind.Relative);
    button2.Text = "Delete";
    ApplicationBar.Buttons.Add(button2);
    button2.Click += new EventHandler(DeleteProject_Click);

    ApplicationBarIconButton button3 = new ApplicationBarIconButton();
    button3.IconUri = new Uri("/Assets/Icons/save.png", UriKind.Relative);
    button3.Text = "Save";
    ApplicationBar.Buttons.Add(button3);
    button3.Click += new EventHandler(SaveProject_Click);
}

The selectionchanged handler is just to store the value in a string called "theFileName"; There is also some manipulation of the appbar buttons here.

Was it helpful?

Solution

Your problem is, if you select an item in your list box, then click delete button. SelectionChanged event will be fired right after the line

SavePanel.DataContext = null; 

This happen because your SavePanel selected index has change to -1 when you clear the Datacontext and rise the event. This cause NullReferenceException. There're several ways to bypass this. One suggestion is check SavePanel.DataContext in SelectionChanged event. Add this code at the start of the event

if(SavePanel.DataContext == null)
   return; //if save panel data context is null then do nothing
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top