|
-
December 14th, 2010, 02:19 PM
#1
Object reference not set to an instance of an object
I am coding an application that can store information in a listbox and save it to text file.
I am trying to code a right click context menu for the listbox. I have successfully implemented a messagebox that comes up when the user right clicks the listbox and it contains no data....but I noticed when testing...if you click OK on the messageboard and quickly right click the listbox again...the application crashes with an "Object reference not set to an instance of an object" message.
If I could just code it to do nothing when right clicked and also have a working context menu that would be great....here is the code below:
private ContextMenuStrip listboxContextMenu;
private void Form1_Load(object sender, EventArgs e)
{
listboxContextMenu = new ContextMenuStrip();
listboxContextMenu.Opening += new CancelEventHandler(listboxContextMenu_Opening);
listBox1.ContextMenuStrip = listboxContextMenu;
}
private void listboxContextMenu_Opening(object sender, CancelEventArgs e)
{
//Clear the menu and add custom items
listboxContextMenu.Items.Clear();
listboxContextMenu.Items.Add(string.Format("Edit - {0}", listBox1.SelectedItem.ToString()));
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
//Select the item under the mouse pointer
listBox1.SelectedIndex = listBox1.IndexFromPoint(e.Location);
if (listBox1.SelectedIndex != -1)
{
listboxContextMenu.Show();
}
else
{
MessageBox.Show("Add an item to the list first.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|