Can't access checked property of menu item created with code outside the designer

144 views Asked by At
private void Form_Shown(object sender, EventArgs e)
{
    // Load Settings
    this.tsmiDuplexEnabled.Checked = Properties.Settings.Default.DuplexEnabled;
    this.tsmiRemoveBlanks.Checked = Properties.Settings.Default.AutoDiscardBlanks;

    this.tsmiColorMode.DropDownItems[Properties.Settings.Default.ColorMode].Checked = true;
}

The last line does not work because it doesn't find the checked property, although there are many available properties. Any idea how I can get at that property?

1

There are 1 answers

1
Slippery Pete On BEST ANSWER

You need to cast it as a ToolStripMenuItem to get the Checked property. Note that separators are not ToolStripMenuItem so you can't blindly cast every DropDownItem as a ToolStripMenuItem.

For example:

foreach (ToolStripItem tsi in item.DropDownItems)
{
    if (tsi is ToolStripMenuItem)
        ((ToolStripMenuItem)tsi).Checked = true;
}

In your case it looks like you won't accidentally get a separator, so this should work:

((ToolStripMenuItem)this.tsmiColorMode.DropDownItems[Properties.Settings.Default.ColorMode]).Checked = true;