Question

I have a listview which has the view mode of details and has a contextmenustrip for deleting an item in the selected row. my problem is that when ever I right click on an empty row, it assumes that the selected item is the first item on the list. is there a possible way for the contextmenustrip to only appear in the rows which has a value? this is the code for my delete in contextmenustrip

private void removeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        DialogResult drty = MessageBox.Show("Remove student " +listView2.Items[listView2.FocusedItem.Index].SubItems[1].Text + " from class?","Remove Data",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
        if (drty == DialogResult.OK)
        {
            conek.nonQuery("delete from class_info where class_id = '"+Convert.ToInt32(textBox5.Text)+"' and stud_id = '"+Convert.ToInt32(listView2.Items[listView2.FocusedItem.Index].SubItems[0].Text)+"'");
            ListViewItem lrs = listView2.Items[listView2.FocusedItem.Index];
            listView2.Items.Remove(lrs);
        }
    }
Was it helpful?

Solution

The Opening event of the ContextMenuStrip is likely what you are looking for:

Something like this will prevent it from showing up at all until you have a selected item.

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) 
{
     e.Cancel = this.listView2.SelectedItems.Count <= 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top