mercredi 6 mai 2015

How to prevent NullReferenceException from being thrown in the first place

I'm having some trouble dealing with the "NullReferenceException" that keeps getting thrown.

Exception

You see I'm working with an ICollectionView.

This ICollectionView has a filter I use to search a DataGrid.

In this same datagrid, there is a SelectedItem attribute that is bound to a property called SelectedUser also within the same ViewModel.

<DataGrid x:Name="principalDataGrid"
          ItemsSource="{Binding PrincipalView, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
          SelectedItem="{Binding SelectedUser, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

The problem is, when ever I search for something that isn't there, the above exception gets thrown as seen in the image.

This is my property

    public string Member
    {
        get
        {
            // The exception Highlights this when thrown.
            return SelectedUser.member;
        }
        set 
        {
            SelectedUser.member = value;
            OnPropertyChanged("Member");
        }
    }

To a degree I can understand what's happening. When the filter is invoked, it narrows down the number of items the Datagrid displays according to what's been typed in as the search parameter. How ever when what you type in that TextBox is not found, the DataGrid will be empty and the SelectedItem becomes null.

The thing is, instead of catching the exception, I need to ensure it never happens in the first place. i.e (The same property as above with a modification):

    public string Member
    {
        get
        {
            if (SelectedUser != null)
                return SelectedUser.member;
            else
                // What would I put here to avoid the error?
                return .................;
        }
        set 
        {
            if (SelectedUser != null)
                SelectedUser.member = value;
            OnPropertyChanged("Member");
        }
    }

I just intend for the datagrid to come up empty when what's being searched for / filtered is not there in it with no need for an error message.

Aucun commentaire:

Enregistrer un commentaire