简体   繁体   中英

Object reference not set to an instance of an object c#

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM