How to use the MaskedTextBox control in WinForms?
MaskedTextBox is a WinForm control designed for inputting formatted text, restricting users to input content in a specified format.
Here are the steps to use MaskedTextBox:
- Create a WinForm application in Visual Studio.
- Drag a MaskedTextBox control onto the window in the design view.
- In the properties window, you can set the Mask property, which specifies the format of the text to be entered. For example, setting it to “000-000-0000” means the input text must be in the format of three numbers, a hyphen, three numbers, a hyphen, and four numbers.
- Other properties can be set, such as the PromptChar property (used to specify a placeholder when no characters are entered) and the PasswordChar property (used to specify a placeholder for password characters).
- You can access the Text property of the MaskedTextBox control in the code to retrieve or modify the value of the control.
Here is an example code using MaskedTextBox:
using System;
using System.Windows.Forms;
namespace MaskedTextBoxExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string phoneNumber = maskedTextBox1.Text;
MessageBox.Show("Phone number: " + phoneNumber);
}
}
}
In the example above, when the user clicks the btnSubmit button, the value of the MaskedTextBox control is displayed in a message box.
Please note that the MaskedTextBox control can only restrict the format of user input, but cannot validate the validity of the input content. In cases where validation of the input content is needed, regular expressions or other methods can be used for validation.