Question

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.

Était-ce utile?

La solution

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;
    }

}

Autres conseils

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top