Working with Menus and Dialogue Boxes

MenuStrip builds the menu bar item by item, ContextMenuStrip answers right-clicks, and dialogs pause the conversation: ShowDialog() returns a DialogResult you must check before acting.

10 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The till grows a File menu

ShopKeeper's form is filling with buttons: New bill, Save, Print, Day report, Settings, Exit... The counter looks like a cockpit, and Mehta Uncle's nephew keeps pressing Print by mistake.

Every serious Windows program solved this decades ago with 2 furniture pieces: the menu bar along the top (File, Edit, Help) and dialog boxes that step in when a task needs a focused conversation: which file? which folder? are you sure?

Both arrive from the same Toolbox as everything else.

Theory

MenuStrip: the bar and its items

Drag a MenuStrip onto the form: it docks along the top and shows a type-here box. Type File, then under it New bill, Save bill, Exit: each entry becomes a ToolStripMenuItem with its own Click event, handled exactly like a button's.

Two polish properties examiners like:

  • access keys: Text of &File makes Alt+F open it (the & underlines F)
  • ShortcutKeys: assign Ctrl+S to Save bill, and the menu shows it

A ContextMenuStrip is the same idea for right-clicks: build it, then point a control's ContextMenuStrip property at it.

Theory

Dialogs: modal conversations

A dialog box is a window opened with ShowDialog(): it is modal, meaning the opening form freezes until the dialog closes. Compare Show(), which opens a modeless window that lives alongside.

The dialog's answer comes back as a DialogResult: OK, Cancel, Yes, No...

.NET ships ready-made dialog components: OpenFileDialog, SaveFileDialog (both expose FileName), ColorDialog (Color), FontDialog (Font). They sit in the component tray, faceless until summoned.

Practical

Save bill, the complete conversation

Private Sub mnuSaveBill_Click(sender As Object, e As EventArgs) _
        Handles mnuSaveBill.Click
    dlgSave.Filter = "Text files|*.txt"
    dlgSave.FileName = "bill-" & Now.ToString("dd-MM-yyyy")

    If dlgSave.ShowDialog() = DialogResult.OK Then
        ' user pressed Save: the chosen path is in dlgSave.FileName
        lblStatus.Text = "Saved: " & dlgSave.FileName
    Else
        lblStatus.Text = "Save cancelled"
    End If
End Sub

Private Sub mnuExit_Click(sender As Object, e As EventArgs) _
        Handles mnuExit.Click
    Dim answer As DialogResult = MessageBox.Show( _
        "Close ShopKeeper?", "Confirm", MessageBoxButtons.YesNo)
    If answer = DialogResult.Yes Then Me.Close()
End Sub

Quiz

A student writes: dlgSave.ShowDialog() : SaveToFile(dlgSave.FileName) without checking anything. When does this go wrong?

  1. Whenever the user presses Cancel: the code saves anyway, to whatever FileName held
  2. Never: ShowDialog() only returns when the user picks a valid file
  3. Always: ShowDialog() must be assigned to a variable or it will not open
  4. Only if the Filter property was not set
Show the answer

Whenever the user presses Cancel: the code saves anyway, to whatever FileName held

ShowDialog() returns a DialogResult for BOTH buttons: Save gives OK, but Cancel returns too, with FileName still holding whatever was there (the suggested name, or last time's choice). Ignoring the result means Cancel silently saves anyway: data written that the user explicitly declined. The fix is the pattern in the listing: If ... = DialogResult.OK Then. Option B credits the dialog with enforcement it does not do. Option C is false (the return value may be compared directly), and Filter (option D) only narrows the file-type list; it validates nothing.

Think first

Modal or modeless: rule on 3 windows

Three ShopKeeper windows: (1) Are you sure you want to delete this bill?, (2) a floating calculator the cashier keeps beside the till, (3) choose the file to import. ShowDialog() or Show() for each, and why?

Show the answer

(1) ShowDialog(): a destructive confirmation must be answered before anything else happens; blocking is the point. (3) ShowDialog(): the import cannot proceed without a file, so the flow must wait. (2) Show(): the calculator serves WHILE billing continues; freezing the till for it would be hostile. The rule in one line: if the program cannot sensibly continue without the answer, modal; if the window assists alongside, modeless. Defaulting everything to modal is the beginner tell.

Watch out

Menu and dialog manners

Check DialogResult, always: the quiz bug ships in real software depressingly often.

Menu events are per-item: handle mnuSaveBill.Click, not some general menu event; each ToolStripMenuItem is its own control.

Do not stack modals: a modal opening a modal opening a MessageBox traps users 3 doors deep; flatten the flow.

MsgBox vs MessageBox.Show: both legal; the .NET form returns DialogResult and reads consistently beside the other dialogs, so prefer it in new code.

Theory

Conventions are free usability

Put Save under File with Ctrl+S and every Windows user who has ever used Notepad already knows your program: that is the quiet power of menu conventions (File first, Help last, Exit at File's bottom). BCA402-02's UI/UX subject will call this the principle of matching user expectations. ShopKeeper's face is now complete: controls, containers, grid, tray workers, menus and dialogs. One lesson remains in Unit 3: what happens when the code behind all this goes wrong, and VB.NET's 2 schools of error handling.

Summary

Key takeaways

  • MenuStrip builds the menu bar from ToolStripMenuItems, each with its own Click event.
  • &File gives Alt+F access; ShortcutKeys attaches Ctrl+S style shortcuts; ContextMenuStrip handles right-clicks.
  • Dialogs open with ShowDialog(): modal, blocking, returning a DialogResult; Show() opens modeless companions.
  • Always test If dlg.ShowDialog() = DialogResult.OK before using the result: Cancel returns too.
  • Ready-made: OpenFileDialog/SaveFileDialog (FileName), ColorDialog, FontDialog; MessageBox.Show returns DialogResult.
  • Modal when the flow must wait; modeless when the window assists alongside.
  • Memory hook: menus organise commands, dialogs pause for answers, and Cancel always returns.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Introduction to Windows controls

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Working with Menus and Dialogue Boxes · .NET Programming · Gri-Learn