0

Fixed it: Casted wrong, should be ToolStripMenuItem, not just MenuItem.

Tried searching msdn and SO but can't figure this out. I'm trying to use the text in a MenuStrip in a switch case, it worked earlier, but then it suddenly gave me a NullRefrence, where am I going wrong? I started a blank project to test, so this code snippet is the only this in it currently.

private void panelSelectMenuItem_Click(object sender, EventArgs e) {
    MenuItem item = sender as MenuItem;

    switch (item.Text) {
        case "Main":
            panelSel(mainPanel);
            break;
        case "Lighting":
            panelSel(lightingPanel);
            break;
        case "Entertainment":
            panelSel(entertainmentPanel);
            break;
        default:
            panelSel(mainPanel);
            break;
    }
}
Hagland
  • 51
  • 1
  • 7
  • Check if `item` is not `null` – Dmitry Bychenko Jun 13 '18 at 10:44
  • What about adding a Null-Check befor the switch-part? – Flocke Jun 13 '18 at 10:45
  • @Flocke, that won't really solve it thouge. I guess the question is why is item null? – Hagland Jun 13 '18 at 10:46
  • because your `sender` is not always `MenuItem` – SᴇM Jun 13 '18 at 10:48
  • `as` is a best effort kind of thing. If sender isn't a instance of `MenuItem` (or a derived type), it will return null. You can test this by rewriting the code as `MenuItem item = (MenuItem)sender;` - When sender isn't a `MenuItem`, it will throw an `InvalidCastException`. – Llama Jun 13 '18 at 10:48
  • @SeM, I know, but I've used MenuItem here before, but turned out it didn't work now. Editet post to reflect the solution. – Hagland Jun 13 '18 at 10:50
  • @Hagland Well yeah, `ToolStripMenuItem` and `MenuItem` are different (I didn't get _"not just MenuItem"_ part). – SᴇM Jun 13 '18 at 10:54

0 Answers0