Reputation: 105
I have a listbox and i'm trying to select an item to display a label. My code is as follows:
private void listBox2_MouseDown(object sender, MouseButtonEventArgs e)
{
ListBox lb = (ListBox)sender;
var selected = lb.SelectedValue.ToString();
//string selected = listBox2.SelectedItem.ToString();
label5.Visibility = Visibility.Visible;
if (selected.ToString() == "Study Date")
{
label5.Content = "Format:YYYYMMDD";
}
if (selected.ToString() == "Patient's Name") label5.Content = "Enter name in string format.";
}
But when i click on an item, i get an error as: Object reference not set to instance of an object
. I cannot enter the code in the Selection changed event, so please tell me how I can go about this. Thanks!
Upvotes: 0
Views: 1053
Reputation: 24022
IIRC the MouseDown()
event fires before the selection is registered. Wouldn't you be better off using the SelectionChanged()
event?
Upvotes: 1
Reputation: 63964
You have a potential issue here:
var selected = lb.SelectedValue.ToString();
You are calling ToString()
even though SelectedValue can be null
Before you call ToString()
make sure SelectedValue
is not null
Upvotes: 1