Search code examples
c#winformslistviewwindows-forms-designercontextmenustrip

make the contextmenustrip item enabled in listview only if the selected row in listview has elements C#


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.


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