Omarrrio
Omarrrio

Reputation: 1142

c# set condition on contextmenustrip

is there anyway to set a condition such as:

when i open a file, it loads some infos on a ListView, the fifth subitem (should be 4 on index count) is loading text, if it is "ETDF", enable an item in the contextmenustrip, if not, disable it, i tried this inside the contextmenustrip but it just gave me an exeption:

if (listView1.SelectedItems[4].ToString() != "ETDF")
        {
            editToolStripMenuItem.Enabled = false;
        }
        else if (listView1.SelectedItems[4].ToString() == "ETDF")
        {
            editToolStripMenuItem.Enabled = true;
        }

am i doing something wrong ?

Upvotes: 0

Views: 654

Answers (3)

terrybozzio
terrybozzio

Reputation: 4532

if (listView1.SelectedItems[4].Text != "ETDF")
        {
            editToolStripMenuItem.Enabled = false;
        }
        else if (listView1.SelectedItems[4].Text == "ETDF")
        {
            editToolStripMenuItem.Enabled = true;
        }

this should solve your problem,error was on calling tostring() when should be text

Upvotes: 1

keyboardP
keyboardP

Reputation: 69372

Set the Enabled property within the Opening event.

private void MyContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
    editToolStripMenuItem.Enabled = (listView1.SelectedItems[4].ToString() == "ETDF");
}

Upvotes: 1

rgrano
rgrano

Reputation: 351

Did you get an ArgumentOutOfRangeException. If so, please check the count.

        if (listView1.Items.Count >= 5)
        {
            if (listView1.SelectedItems[4].ToString() != "ETDF")
            {
                editToolStripMenuItem.Enabled = false;
            }
            else if (listView1.SelectedItems[4].ToString() == "ETDF")
            {
                editToolStripMenuItem.Enabled = true;
            }
        }

Upvotes: 1

Related Questions