C# > UI Programming > Windows Forms > Dialogs and MessageBoxes

Showing a Dialog with User Input (InputDialog)

This code snippet demonstrates how to create a simple InputDialog using Windows Forms. This type of dialog is used to ask the user for a single line of text input.

Code

This snippet creates a new Form, adds a label, a textbox and a button to it. The `ShowDialog` method is used to display the form as a modal dialog. The input from the textbox is returned if the user clicks the 'Ok' button, otherwise an empty string is returned.

using System; 
using System.Windows.Forms;

public class InputDialog
{
    public static string ShowInputDialog(string prompt, string title)
    {
        Form promptForm = new Form()
        {
            Width = 500,
            Height = 150,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            Text = title,
            StartPosition = FormStartPosition.CenterScreen
        };

        Label textLabel = new Label() { Left = 50, Top = 20, Text = prompt, Width = 400 };
        TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
        Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { promptForm.Close(); };

        promptForm.Controls.Add(textBox);
        promptForm.Controls.Add(confirmation);
        promptForm.Controls.Add(textLabel);
        promptForm.AcceptButton = confirmation;

        return promptForm.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }
}

Explanation

  • Creating the Form: A new `Form` object is created and its properties are set (width, height, border style, title, and start position).
  • Adding Controls: A `Label`, `TextBox`, and `Button` are created and added to the form's `Controls` collection. The properties like `Left`, `Top`, and `Width` are used to position the controls on the form.
  • Button Click Event: An event handler is added to the button's `Click` event. When the button is clicked, the `DialogResult` property of the form is set to `DialogResult.OK` which causes the `ShowDialog()` method to return `DialogResult.OK` and close the form.
  • Showing the Dialog: The `ShowDialog()` method is called to display the form modally.
  • Returning the Input: The value from the TextBox is retrieved if the DialogResult is OK. If it's cancelled, an empty string is returned.

How to use the InputDialog

This code shows how to call the `ShowInputDialog` method and handle the returned value. An instance of InputDialog is created and then the static method ShowInputDialog is invoked. The user input captured is then displayed in a message box

InputDialog inputDialog = new InputDialog();
string result = InputDialog.ShowInputDialog("Please enter your name:", "Name Input");

if (!string.IsNullOrEmpty(result))
{
    MessageBox.Show("Hello, " + result + "!");
}

Concepts Behind the Snippet

The InputDialog pattern allows you to create custom dialogs for collecting specific information from the user. By creating your own form, you have full control over the appearance and behavior of the dialog. You can customize it to suit the needs of your application.

Real-Life Use Case

InputDialogs are useful when you need to prompt the user for specific input, such as a file name, a server address, or a user ID. They provide a clean and intuitive way to gather information without cluttering the main application window.

Best Practices

  • Validate the user input. Ensure that the input is in the correct format and within the expected range.
  • Provide clear and concise prompts. Tell the user exactly what information you need.
  • Consider using masked textboxes for sensitive input, such as passwords.
  • Handle the case where the user cancels the dialog.

Alternatives

  • Using a third-party library that provides a built-in input dialog.
  • Creating a custom form with more advanced validation and input controls.

When to Use Them

Use input dialogs when you need to collect a small amount of information from the user in a controlled and modal manner. For complex data entry scenarios, consider using a dedicated form with multiple input fields and validation logic.

FAQ

  • How can I add validation to the input?

    You can add validation logic to the button's click event handler. Before closing the dialog, check if the input is valid. If it's not, display an error message and prevent the dialog from closing.
  • Can I customize the appearance of the dialog?

    Yes, you can customize the appearance of the dialog by modifying the properties of the form and its controls. You can change the font, color, size, and position of the controls.