1

Say i ve a listview with items

apple
banana
beans

ive attached contextmenustrip to the listview, say the contextmenustrip item is add

i want add to be enabled only when i click on the items in the listview not anywhere on the empty list.

Prasad MV
  • 107
  • 2
  • 3
  • 10

2 Answers2

2

Just intercept the Opening event of the ContextMenuStrip component (which occurs before the context menu actually appears) and do something like this:

public partial class Form1 : Form {

    public Form1() {
        this.InitializeComponent();

        this.contextMenuStrip1.Opening += this.contextMenuStrip1_Opening;
    }

    private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {
        this.itemAdd.Enabled = this.listView1.SelectedItems.Count > 0;
    }

}
Eduard Dumitru
  • 3,242
  • 17
  • 31
0

Here is another approach that will stop the ContextMenuStrip control from being brought up at all unless you have selected at least 1 item from the ListView control:

This approach also intercepts the Opening event of the ContextMenuStrip.

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) 
{
     e.Cancel = this.listView1.SelectedItems.Count <= 0;
}
Derek W
  • 9,708
  • 5
  • 58
  • 67