Dinesh
Dinesh

Reputation: 537

NullReferenceException when Double Clicked on ListBox entry

I've listBox in wpf application which contains two entries. I've written Double click event function for it.But when I click on any single entry, it shows me NullReferenceException. Exception is at line - if (listBox1.SelectedItem != null)

I just want single entry on which I'll click. How should I proceed?

My Double click event is as follows:

private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        //Submit clicked Entry
        if (listBox1.SelectedItem != null)
        {
            Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)listBox1.SelectedItem;
            if (!entryToPost.isSynced)
            {
                //Check if something is selected in selectedProjectItem For that item
                if (entryToPost.ProjectNameBinding == "Select Project")
                    MessageBox.Show("Please Select a Project for the Entry");
                else
                    Globals._globalController.harvestManager.postHarvestEntry(entryToPost);
            }
            else
            {
                //Already synced.. Make a noise or something
                MessageBox.Show("Already Synced;TODO Play a Sound Instead");
            }
        }
        else
        {
            throw new NullReferenceException("Entry does not exist");
        }

     }

I assign eventhandler as,

InitializeComponent();
listBox1.MouseDoubleClick += new MouseButtonEventHandler(listBox1_MouseDoubleClick);

Upvotes: 0

Views: 592

Answers (2)

Microsoft DN
Microsoft DN

Reputation: 10030

I have found something as follows . Give it a try. It will display the selected item text on double click. You can modify it as per your requirement.

void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
     int index = this.listBox1.IndexFromPoint(e.Location);
     if (index != System.Windows.Forms.ListBox.NoMatches)
     {
         MessageBox.Show(index.ToString());
     }
}

Upvotes: 0

vendettamit
vendettamit

Reputation: 14687

Try adding this line rather using listBox1 directly:

private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        //Submit clicked Entry
         if(sender is ListBox)
         {
            var listBoxRef = sender as ListBox;
            ...
            if (listBoxRef.SelectedItem != null)
            .....
            ....
      }
    }

Upvotes: 1

Related Questions