如何在文本框中只写一次字符



我正在制作一个文本框来输入一些Product的价格,我不希望用户多次输入".""."不能是第一个字符(我知道怎么做)。但我需要使文本框接受这个字符"。"不超过一次。如何?不,我不想用MaskedTextBox

把它放在你的文本框的KeyPress事件中

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    string inputChar = e.KeyChar.ToString();
    if (inputChar == ".")
    {
        if (textBox1.Text.Trim().Length == 0)
        {
            e.Handled = true;
            return;
        }
        if (textBox1.Text.Contains("."))
        {
            e.Handled = true;
        }
    }
}

试试这个

private void textBox1_TextChanged(object sender, EventArgs e)
{
  if (textBox1.Text.IndexOf('.') != textBox1.Text.LastIndexOf('.'))
  {
     MessageBox.Show("More than once, not allowed");
     textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
  }
}

最新更新