[英]Input string was not in a correct format occurs in c#
private void txtbox_BattMmnt_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back /*|| e.KeyChar == (char)5*/ || e.KeyChar == 46)
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("Please Enter Only Numeric Value", "Error", MessageBoxButtons.OK);
}
double i=Convert.ToDouble(txtbox_BattMmnt.Text);
if (i >=2.9 || i <= 3.35)
{ e.Handled = false; }
else
{
e.Handled = true;
MessageBox.Show("Please Enter Only from 2.9 to 3.35", "Error", MessageBoxButtons.OK);
}
}
The error appears in double i=Convert.ToDouble(txtbox_BattMmnt.Text);
错误出现在double i=Convert.ToDouble(txtbox_BattMmnt.Text);
What shall I do? 我该怎么办? I tried Regex but it wont satisfy my range of values to be entered in the text box. 我尝试过Regex,但它不满足要在文本框中输入的值范围。
Try this: 尝试这个:
double d;
if(!double.TryParse(txtbox_BattMmnt.Text, out d))
{
// invalid text in textbox, not convertable to double
}
This allows for arbitrary user input without crashing your app. 这允许任意用户输入而不会崩溃您的应用程序。
Try this 尝试这个
private void txtbox_BattMmnt_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back /*|| e.KeyChar == (char)5*/ || e.KeyChar == 46)
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("Please Enter Only Numeric Value", "Error", MessageBoxButtons.OK);
return;//return if it is not numeric.
}
double i = 0;
Double.TryParse(txtbox_BattMmnt.Text, out i);
if (i <= 2.9 || i >= 3.35)
{ e.Handled = false; }
else
{
e.Handled = true;
MessageBox.Show("Please Enter Only from 2.9 to 3.35", "Error", MessageBoxButtons.OK);
}
}
private void txtbox_BattMmnt_Validating(object sender, CancelEventArgs e)
{
TextBox txtbox_BattMmnt = (TextBox)sender;
double d; Double.TryParse(txtbox_BattMmnt.Text, out d);
if ((d <= 2.8) || (d >= 3.36))
{
MessageBox.Show("Please Enter Only from 2.9 to 3.35", "Error", MessageBoxButtons.OK);
}
txtbox_BattMmnt.Text = String.Empty;
}
I tried this.....it worked out. 我尝试了这个。 thank u guys 谢谢你们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.