如何阻止文本框中的第一个字符成为’。’?

这是我目前的代码:

private void textBox_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && e.KeyChar != '.'; if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) e.Handled = true; } 

KeyPress不足以进行这种validation。 绕过它的一种简单方法是使用Ctrl + V将文本粘贴到文本框中。 或者上下文菜单,根本没有关键事件。

在这种特定情况下,TextChanged事件将完成工作:

  private void textBox_TextChanged(object sender, EventArgs e) { var box = (TextBox)sender; if (box.Text.StartsWith(".")) box.Text = ""; } 

但是,validation数值还有很多。 您还需要拒绝诸如1.1.1或1.-2之类的内容。 请改用Validating事件。 在表单上删除ErrorProvider并实现如下事件:

  private void textBox_Validating(object sender, CancelEventArgs e) { var box = (TextBox)sender; decimal value; if (decimal.TryParse(box.Text, out value)) errorProvider1.SetError(box, ""); else { e.Cancel = true; box.SelectAll(); errorProvider1.SetError(box, "Invalid number"); } } 

您可能希望使用TextChanged事件,因为用户可以粘贴值。 为了获得满足要求的最佳体验,我建议简单地删除任何领先. 字符。

 void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text.StartsWith(".")) { textBox1.Text = new string(textBox1.Text.SkipWhile(c => c == '.').ToArray()); } } 

这并不能解决仅使用数字的要求 – 如果是这种情况,问题中并不清楚。

这也适用于复制和粘贴。

  private void textBox1_KeyUp(object sender, KeyEventArgs e) { int decimalCount=0; string rebuildText=""; for(int i=0; i 

你可以试试这个:

 private void TextBox_TextChanged(object sender, EventArgs e) { TextBox.Text = TextBox.Text.TrimStart('.'); }