Do not show context menu if nothing is selected

I like the context menu to be displayed only if the item is really selected in the list in the C # winforms application.

Currently, I can select an item if it clicked correctly, and I can turn off the right-click menu if nothing is selected, however I do not want the menu to even display.

How can I do that?

private void genPassMenu_Opening(object sender, CancelEventArgs e) { genPassMenu.Enabled = lstPasswords.SelectedIndex > 0; genPassMenu.Visible = lstPasswords.SelectedIndex > 0; } 

I tried both of these situations myself, and it only works for resolved ones.
Perhaps discovery is not the right choice? Tx

+6
c #
source share
4 answers

Try the following:

 private void genPassMenu_Opening(object sender, CancelEventArgs e) { //if (lstPasswords.SelectedIndex == -1) e.Cancel = true; e.Cancel = (lstPasswords.SelectedIndex == -1); } 
+11
source share

Easy

  private void genPassMenu_Opening(object sender, CancelEventArgs e) { e.Cancel = (lstPasswords.SelectedIndex == 0); } 
+4
source share

I usually set the properties of each context menu item according to its relevance for the selected selected GUI element. Perhaps by setting a visible attribute for each menu item, and not the entire menu, you can get the desired results.

0
source share
 private void genPassMenu_Opening(object sender, CancelEventArgs e) { //genPassMenu.Enabled = lstPasswords.SelectedIndex > 0; //genPassMenu.Visible = lstPasswords.SelectedIndex > 0; e.Cancel = (lstPasswords.SelectedIndex <= 0); } 

I saw when the opposite was the case above, I changed the code a bit. For some reason, equality also did not work.

0
source share

All Articles