我需要我的文本框只接受带小数点后一位的数字。我创建了一个只接受数值的函数。现在我需要一个只接受一个小数点的帮助:
private void txtOpenBal_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
foreach (char ch in e.Text)
if (!(Char.IsDigit(ch) || ch.Equals('.')))
{
e.Handled = true;
}
}
它接受多个小数点
答案 0 :(得分:1)
private void TextBox_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
{
// Here e.Text is string so we need to convert it into char
char ch = e.Text[0];
if ((Char.IsDigit(ch) || ch == '.'))
{
//Here TextBox1.Text is name of your TextBox
if (ch == '.' && TextBox1.Text.Contains('.'))
e.Handled = true;
}
else
e.Handled = true;
}
答案 1 :(得分:1)
正如@ehh所说使用正则表达式我们可以实现这个。添加命名空间System.Text.RegularExpressions;
private void TextBox_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
{
Regex objregex = new Regex(@"^\d*\.\d{1}$");
if (objregex.IsMatch(txtDomain.Text))
{
//do whatewer you want
}
else
{
//do whatewer you want
}
}