[英]If I start input with decimal point in my textbox in C#, I get Input Format Exception
I'm calculating Fabric Weight in Decimal. 我正在以十进制计算织物重量。
If I enter 0.071, the program works fine. 如果输入0.071,则程序运行正常。 but if I enter .071 I get input format exception error which is dumb. 但是,如果输入.071,我会得到愚蠢的输入格式异常错误。 I want to remove this irritating input format exception error, because a user forgot to enter 0.071. 我想删除此令人讨厌的输入格式异常错误,因为用户忘记输入0.071。
here are the details. 这是详细信息。
Exception I'm getting. 我得到了例外。
try { if (System.Text.RegularExpressions.Regex.IsMatch(textBox28.Text, "[^0-9^+]")) { MessageBox.Show("Please enter only numbers."); textBox28.Clear(); textBox28.Focus(); } } catch (ArgumentOutOfRangeException err){ MessageBox.Show(err.ToString()); } try { // Input format error 702 FabricWeight = float.Parse(textBox28.Text); } catch (FormatException err) { MessageBox.Show(err.ToString());
Before FabricWeight = float.Parse(textBox28.Text);
在FabricWeight = float.Parse(textBox28.Text);
you could add: 您可以添加:
if(textBox28.Text.StartsWith('.')
{
textBox28.Text = string.Format("{0}{1}", 0, textBox28.Text);
}
And as Jon said - using TryParse
is way more efficient. 正如乔恩所说-使用TryParse
效率更高。
Try this code in event key-press of textbox, its better way: 在文本框的事件按键中尝试以下代码,它的更好方法是:
private void textBox28_KeyPress(object sender, KeyPressEventArgs e)
{
if ( System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[^0-9^+.]") )
e.Handled = true;
if (e.KeyChar == '.' && textBox28.Text.Length == 0)
e.Handled = true;
int i = 0;
foreach (char cc in textBox28.Text)
if (cc == '.')
i++;
if (i >= 1 && e.KeyChar == '.')
e.Handled = true;
}
I test it now. 我现在测试。 please check this. 请检查一下。
Credits to @ Bruniasty 归功于 @ Bruniasty
This works. 这可行。
"Below this method" I'm storing result in Fabric Weight, you can use this for your program and store to any variable you like after "Try Parsing". “在此方法下面”我将结果存储在“织物权重”中,您可以将其用于程序,并在“尝试解析”之后存储到所需的任何变量中。
private static void TryToParse(string value)
{
double number;
bool result = double.TryParse(value, out number);
if (result)
{
FabricWeight = number;
}
else
{
if (value == null) value = "";
}
}
Wrote this and worked. 写下并工作。
TryToParse(textBox28.Text);
for more information: Visit this link MSDN Library: TryParse 有关更多信息:请访问此链接MSDN库:TryParse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.