我有一个文本框供用户输入数字。
当用户输入到文本框时,格式应该是这样的
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;
}
}
如果您需要任何帮助,请告诉我。
关于c# - 如何在TextBox中自动在2位数字后插入连字符 "-"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28038145/