如何格式化文本框以在用户键入时显示 SSN [英] How to format textbox to display SSN as the user types
问题描述
我有一个我想实时格式化的文本框:###-##-####
作为用户输入.
I have a textbox which I would like to format in real time: ###-##-####
as the user types.
我有以下代码:
private bool bFlag;
private void tbSSN_TextChanged(object sender, EventArgs e)
{
string str = tbSSN.Text;
if (!bFlag)
{
if (str.Length == 3 || str.Length == 6)
{
tbSSN.Text += "-";
bFlag = true;
tbSSN.SelectionStart = tbSSN.Text.Length;
}
else if (str.Length > 11)
{
tbSSN.Text = tbSSN.Text.Remove(tbSSN.Text.Length - 1);
tbSSN.SelectionStart = tbSSN.Text.Length;
}
}
else
{
bFlag = false;
}
}
唯一的问题是,当我按下退格键并再次尝试输入数字时,它允许我输入以下格式:#####--####
或 ##-#####-##
The only issue is, when I hit backspace and try to enter the numbers again, it is allowing me to enter this format: #####--####
or ##-#####-##
我知道我必须添加一个 KeyPress
事件以确保解决上述问题,但我不确定如何添加它.
I know I have to add a KeyPress
event to ensure the above issue is resolved, but I am not sure how I would add it.
我将如何编码 KeyPress
事件?
How would I code the KeyPress
event?
这是一个 WinForm 应用程序.
It is a WinForm application.
推荐答案
使用 MaskedTextBox 而不是普通的 TextBox 并定义一个 掩码 为您的文本框.
Use MaskedTextBox instead of normal TextBox and define a Mask for your TextBox.
yourMaskedTextBox.Mask = "000-00-0000";
这篇关于如何格式化文本框以在用户键入时显示 SSN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!