我希望文本框验证仅允许一个.
值和一个数字。表示我的文本框值应仅包含数字和一个.
值。值应类似于123.50。
我正在使用代码在值的末尾添加.oo
或.50
值。
我的代码是
double x;
double.TryParse(tb.Text, out x);
tb.Text = x.ToString(".00");
它占用了键盘上的所有键,但是我只想取数字和一个
.
值。
最佳答案
为您的文本框添加Control.KeyPress事件处理程序。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)) //bypass control keys
{
int dotIndex = textBox1.Text.IndexOf('.');
if (char.IsDigit(e.KeyChar)) //ensure it's a digit
{ //we cannot accept another digit if
if (dotIndex != -1 && //there is already a dot and
//dot is to the left from the cursor position and
dotIndex < textBox1.SelectionStart &&
//there're already 2 symbols to the right from the dot
textBox1.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
}
else //we cannot accept this char if
e.Handled = e.KeyChar != '.' || //it's not a dot or
//there is already a dot in the text or
dotIndex != -1 ||
//text is empty or
textBox1.Text.Length == 0 ||
//there are more than 2 symbols from cursor position
//to the end of the text
textBox1.SelectionStart + 2 < textBox1.Text.Length;
}
}
您可以通过设计器或在构造函数中进行如下操作:
public Form1()
{
InitializeComponent();
//..other initialization
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
我还添加了几项检查,以确保您不仅可以在文本末尾插入数字,而且可以在任何位置插入数字。同样带点。它控制您在点右边的位数不超过2位。我已经使用TextBox.SelectionStart Property来获取光标在文本框中的位置。检查此线程以获取有关此信息的更多信息:How do I find the position of a cursor in a text box?
关于c# - 文本框验证是否允许一个“。 ”值C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13774890/