我有一个文本框供用户输入数字。
当用户输入到文本框时,格式应如下所示
01-22-34-40-33
我想在TextChanged事件处理程序的2位数字后插入“-”。
我做这样的事情,但是没有工作:
if(txtRandomThirdTypeSales.Text.Length == 2)
{
txtRandomThirdTypeSales.Text += "-";
}
else if (txtRandomThirdTypeSales.Text.Length == 5)
{
txtRandomThirdTypeSales.Text += "-";
}
else if (txtRandomThirdTypeSales.Text.Length == 8)
{
txtRandomThirdTypeSales.Text += "-";
}
else if (txtRandomThirdTypeSales.Text.Length == 11)
{
txtRandomThirdTypeSales.Text += "-";
}
您能否以这种方式尝试,这可能对您有所帮助。
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string sVal = textBox1.Text;
if (!string.IsNullOrEmpty(sVal) && e.KeyCode != Keys.Back)
{
sVal = sVal.Replace("-", "");
string newst = Regex.Replace(sVal, ".{2}", "$0-");
textBox1.Text = newst;
textBox1.SelectionStart = textBox1.Text.Length;
}
}
让我知道您是否需要任何帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句