格式文本不同的方式,如果TextLength = 13使用按键
本文关键字:TextLength 如果 文本 方式 格式 | 更新日期: 2023-09-27 18:09:08
我有自动格式化电话号码的代码,格式为12 3456-7890
1234567890 = 12 3456-7890 (TextLength = 12)
我想让if TextLength = 13的格式是这样的
12345678901 = 12 34567-8901 (TextLength = 12)或者换句话说,将"-"的位置右移1位,并在最后一个字符上添加最后一个数字
我的实际代码
private void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
}
else
{
if (txtFonecom.TextLength == 2)
{
txtFonecom.Text = txtFonecom.Text + " ";
txtFonecom.SelectionStart = 3;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 7)
{
txtFonecom.Text = txtFonecom.Text + "-";
txtFonecom.SelectionStart = 8;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 13)
{
//here i have to change format from 12 3456-7890 to 12 34567-8901
}
}
}
而不是手动处理按键,我建议使用mask 00 0000-0000
的MaskedTextBox控件,因为该控件可以自动为您格式化输入。
假设您仍然喜欢使用文本框解决方案,下面是解决方案:
private void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
}
else
{
if (txtFonecom.TextLength == 2)
{
txtFonecom.Text = txtFonecom.Text + " ";
txtFonecom.SelectionStart = 3;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 7)
{
txtFonecom.Text = txtFonecom.Text + "-";
txtFonecom.SelectionStart = 8;
txtFonecom.SelectionLength = 0;
}
if (txtFonecom.TextLength == 12)
{
int caretPos = txtFonecom.SelectionStart;
txtFonecom.Text = txtFonecom.Text.Replace("-", string.Empty).Insert(8, "-");
txtFonecom.SelectionStart = caretPos;
}
}
}
请记住,当用户删除数字时,您需要处理格式
无论用户在任何地方删除或添加数字,该代码都将保持" "
和"-"
在他们的位置:
void txtFonecom_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back)
{
if (txtFonecom.TextLength == 2)
{
txtFonecom.Text = txtFonecom.Text + " ";
txtFonecom.SelectionStart = 3;
}
if (txtFonecom.TextLength >= 7 && txtFonecom.TextLength < 12)
{
if (txtFonecom.Text.Substring(2, 1) == " ") //check if " " exists
{ }
else //if doesn't exist, then add " " at index 2 (character no. 3)
{
txtFonecom.Text = txtFonecom.Text.Replace(" ", String.Empty);
txtFonecom.Text = txtFonecom.Text.Insert(2, " ");
}
txtFonecom.Text = txtFonecom.Text.Replace("-", String.Empty); //now add "-" at index 7 (character no. 8)
txtFonecom.Text = txtFonecom.Text.Insert(7, "-");
txtFonecom.SelectionStart = txtFonecom.Text.Length;
}
if (txtFonecom.TextLength >= 12)
{
if (txtFonecom.Text.Substring(2, 1) == " ") //check if " " exists
{ }
else //if doesn't exist, then add " " at index 2 (character no. 3)
{
txtFonecom.Text = txtFonecom.Text.Replace(" ", String.Empty);
txtFonecom.Text = txtFonecom.Text.Insert(2, " ");
}
txtFonecom.Text = txtFonecom.Text.Replace("-", String.Empty); //now add "-" at index 8 (character no. 9)
txtFonecom.Text = txtFonecom.Text.Insert(8, "-");
txtFonecom.SelectionStart = txtFonecom.Text.Length;
}
}
}
或者如果您只想要textbox
中的数字,则使用
if ((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57)