C# 在文本框中检查负输入
我正在尝试验证Windows窗体应用程序中的文本框。文本框接受任何数字(应该是十进制,但也只接受整数)。我不希望数字是负数,但即使添加了if语句,即使输入的数字是否定的,应用程序仍然接受它。我不确定我做错了什么C# 在文本框中检查负输入,c#,winforms,validation,input,C#,Winforms,Validation,Input,我正在尝试验证Windows窗体应用程序中的文本框。文本框接受任何数字(应该是十进制,但也只接受整数)。我不希望数字是负数,但即使添加了if语句,即使输入的数字是否定的,应用程序仍然接受它。我不确定我做错了什么 try { //Different operations being done here that use the input from txtEnterTotal.Text } catch { decimal entertotal = Convert.ToDecima
try
{
//Different operations being done here that use the input from txtEnterTotal.Text
}
catch
{
decimal entertotal = Convert.ToDecimal(txtEnterTotal.Text);
if (entertotal <= 0)
{
MessageBox.Show("Please enter a valid number for the total field.", "Entry Error");
}
}
试试看
{
//这里执行的不同操作使用来自txtEnterTotal.Text的输入
}
抓住
{
decimal entertotal=Convert.ToDecimal(txtEnterTotal.Text);
如果(entertotal我认为验证您的输入是否为数字和十进制的最佳方法是使用如下代码。正如评论人@MickyD建议的那样,decimal.TryParse
如下:
try
{
//Different operations being done here that use the input from txtEnterTotal.Text
}
catch(Exception ex)
{
// catch the exception and DO something with it.
System.Diagnostics.Trace.TraceError("Error before try/parse: {0}", ex);
//decimal entertotal = Convert.ToDecimal(txtEnterTotal.Text);
// old code ^^^^^^
// new code
if (decimal.TryParse(txtEnterTotal.Text, out decimal entertotal))
{
if (entertotal <= decimal.Zero)
{
MessageBox.Show("Please enter a valid number for the total field.", "Entry Error");
}
}
else
{
MessageBox.Show(string.Format("Failed to parse value: {0}", txtEnterTotal.Text));
}
}
试试看
{
//这里执行的不同操作使用来自txtEnterTotal.Text的输入
}
捕获(例外情况除外)
{
//捕获异常并对其进行处理。
System.Diagnostics.Trace.TraceError(“try/parse之前的错误:{0}”,ex);
//decimal entertotal=Convert.ToDecimal(txtEnterTotal.Text);
//旧代码^^^^^^
//新代码
if(decimal.TryParse(txtEnterTotal.Text,out decimal entertotal))
{
如果(entertotal示例代码的一个问题是您在catch
块中执行Convert.ToDecimal(txtenertotal.Text)
,但如果txtenertotal.Text
不是有效数字,则会引发异常,因此该异常现在将被取消处理
既然您说您确实想使用try/catch
来验证文本框,那么基本模式就是尝试转换try
块中的数字,如果失败,则在catch块中采取措施(不会引发另一个异常)
例如:
private void btnValidate_Click(object sender, EventArgs e)
{
try
{
// Here we perform the operation that might throw an exception
decimal value = Convert.ToDecimal(txtEnterSubtotal.Text);
// If we get here, no exception was thrown
MessageBox.Show("Thank you");
}
catch
{
// Since there was an exception, show a message and clear the textbox
MessageBox.Show("Please enter a valid, positive number");
txtEnterSubtotal.Clear();
txtEnterSubtotal.Focus();
}
}
然而,使用try/catch
进行简单的错误处理是“昂贵的”(捕获调用堆栈是有代价的),而且这也不是它们的预期目的(它们应该用于异常事件,而不是控制正常的程序流)
现在是了解数字类型所具有的方法的好时机。此方法接收字符串
进行解析,如果成功,它将数字类型的out
参数设置为转换后的值。最好的部分是它返回一个表示成功的bool
,因此我们可以在if
条件下使用它如果字符串解析失败,请执行以下操作
例如,您可以在验证方法中使用此代码,而不再需要使用try/catch
,因为我们使用TryParse
进行验证:
private void btnValidate_Click(object sender, EventArgs e)
{
// Here we check if `TryParse` does NOT return true (note the exclamation mark), OR
// if the converted number less than zero, where in either case we take some action
if (!decimal.TryParse(txtEnterSubtotal.Text, out decimal value) ||
value < 0)
{
// Show a message, then clear the textbox
MessageBox.Show("Please enter a valid, positive number");
txtEnterSubtotal.Clear();
txtEnterSubtotal.Focus();
}
else
{
MessageBox.Show("Thank you");
}
}
private void btnValidate\u单击(对象发送者,事件参数e)
{
//这里我们检查'TryParse'是否不返回true(注意感叹号),或者
//如果转换后的数字小于零,在任何一种情况下,我们都会采取一些措施
如果(!decimal.TryParse(txtEnterSubtotal.Text,输出十进制值)||
值<0)
{
//显示消息,然后清除文本框
MessageBox.Show(“请输入一个有效的正数”);
txtEnterSubtotal.Clear();
txtEnterSubtotal.Focus();
}
其他的
{
MessageBox.Show(“谢谢”);
}
}
考虑使用Decimal.TryParse()
而不是使用try-catch
。后者通常不应用于正常的程序流。此外,Convert.ToDecimal
可以在xxx.TryParse()时引发异常
try/catch
语句的catch
代码块中出现异常时,您只检查是否有否定项,这取决于try
代码块中发生的情况。一般来说,您根本不需要try/catch
代码块中出现异常-请参阅@MickyD's su在C#中,您的优势是可以将输出变量内联:例如,if(decimal.TryParse(txtertotal.Text,out decimal value)){if(value<0){/*负值*/}else{/*不是有效值*/}
我更新了我的代码,也尝试过了,但我的应用程序仍然接受它并执行所有计算,尽管@JimiConvert.ToDecimal(txtEnterTotal.Text)为负数
如果txtEnterTotal.Text
不是有效数字,将引发异常。您可能不希望在catch
块中出现该异常……在catch
块中,该代码在做什么?您在这里执行不同的操作,这些操作使用来自txtEnterTotal的输入。Text在上面,这就是在TextBo中输入值的位置x是必需的。try/catch块应该被删除,如果不是用于其他用途的话。但这不是关于文本框的验证。Text。@Jimi同意,那里应该有一个异常实例,我们应该对它做些什么。--我只是从用户的示例代码开始工作,关注的是Decimal.Parse
问题hand@GlennFeRRE我尝试了你所拥有的,它可以工作,但是当我第一次单击我的计算按钮时,它被接受了,如果我再次单击它,我就会收到消息。它似乎没有第一次捕捉到它。这不是关于捕捉
部分的语法,而是关于的使用。TryParse()
。try/catch
块不再需要了,这就是TryParse()
的内容。@rythm500“这就是我的课本上说要使用的”-我会得到一本不同的课本;)
private void btnValidate_Click(object sender, EventArgs e)
{
// Here we check if `TryParse` does NOT return true (note the exclamation mark), OR
// if the converted number less than zero, where in either case we take some action
if (!decimal.TryParse(txtEnterSubtotal.Text, out decimal value) ||
value < 0)
{
// Show a message, then clear the textbox
MessageBox.Show("Please enter a valid, positive number");
txtEnterSubtotal.Clear();
txtEnterSubtotal.Focus();
}
else
{
MessageBox.Show("Thank you");
}
}