0

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!

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hi @icarus, i removed the ToSrting part, my lb.SelectedValue is null, even though i am clicking on an item. :( Thanks!
@user877852: See? that was the issue! mouse_down is not the method you should be handling. At that point nothing has been selected yet. You probably need to handle OnSelectedIndexChanged or something similar. I am not a WPF developer so I can't be 100% sure.
Yeah i figured that its empty. Okay no problem, thanks for the help :)
1

IIRC the MouseDown() event fires before the selection is registered. Wouldn't you be better off using the SelectionChanged() event?

4 Comments

Hi, i dont seem to have an event like that :(
I've always coded it like this <ListBox SelectionChanged="ListBox_SelectionChanged"...>
Hi, i put it in the selection changed event, and its working now! o.O thanks!
Awesome! Glad I could assist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.