如何插入连字符“-"在 TextBox 中自动输入 2 位数字后? [英] How to insert hyphen "-" after 2 digits automatically in TextBox?
本文介绍了如何插入连字符“-"在 TextBox 中自动输入 2 位数字后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本框供用户输入数字.
I have one TextBox for user to input number.
当用户输入到 TextBox 时,格式应该是这样的
When user input to the TextBox then the format should be like this
01-22-34-40-33
01-22-34-40-33
我想在 TextChanged 事件处理程序中的 2 位数字后插入-".
I want to insert "-" after 2 digits in the TextChanged event handler.
我做了类似的事情但没有工作:
I do something like this but no work:
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 += "-";
}
推荐答案
你能试试这个方法吗,这可能对你有帮助.
Can you please try this way,this may be will helpful for you.
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;
}
}
如果您需要任何帮助,请告诉我.
Let me know if you need any help.
这篇关于如何插入连字符“-"在 TextBox 中自动输入 2 位数字后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文