WPF C# NULL exception on combobox selection change
This is selection changed event :
private void cbUsers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedUser = (sender as ComboBox).SelectedItem.ToString();
GetUserInformation();
}
GetUserInformation
is just selecting password from database. Users are deleted from the database and then the following refreshes the ComboBox
items:
public void FillComboBox()
{
cbUsers.ItemsSource = null;
HProDataContext db = new HProDataContext();
var _UserName = (from d in db.users select d.username).ToList();
cbUsers.ItemsSource = _UserName;
}
HProDataContext db = new HProData开发者_开发百科Context();
var _UserID = (from d in db.users where d.username == cbUsers.Text select d.id).SingleOrDefault();
user u = db.users.Single(p => p.id == _UserID);
db.users.DeleteOnSubmit(u);
db.SubmitChanges();
cbUsers.ItemsSource = null;
cbUsers.Text = null;
FillComboBox();
When using this last method it gives such error:
Object reference not set to an instance of an object.
The error falls on this line of the FillComboBox
method:
SelectedUser = (sender as ComboBox).SelectedItem.ToString();
Does anyone have an idea as to what is wrong?
I'd guess that SelectedItem
is null
and therefore you're calling ToString
on nothing.
Consider trying this:
if ((sender as ComboBox).SelectedItem != null)
{
SelectedUser = (sender as ComboBox).SelectedItem.ToString();
}
However, doesn't your ComboBox
have an identifier? This can allow you to refrain from unnecessary conversions with as
:
if (myComboBox.SelectedItem != null)
{
SelectedUser = myComboBox.SelectedItem.ToString();
}
Your event handler is probably getting called when there is no SelectedItem
.
I would write this as:
private void cbUsers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var usersComboBox = (ComboBox)sender;
if (usersComboBox.SelectedItem == null) return;
SelectedUser = usersComboBox.SelectedItem.ToString();
GetUserInformation();
}
Here you are expecting that sender is always a ComboBox, so I would use a cast instead of as
. The exception will let you know if your assumption is wrong.
This will just skip your code if the event handler is called without a selected item.
One possibility is that sender
might not be a ComboBox
.
A problem of using an as
operator without a null
check is you get a NullReferenceException
instead of a InvalidCastException
which is more appropriate
Use an explicit cast instead e.g. ((ComboBox)sender).SelectedItem.ToString();
if you are sure sender
is a ComboBox
; otherwise check for null
before usage.
精彩评论