如何在C#中捕获空/null字符串异常? [英] how do I catch empty/ null String exception in C #?

查看:453
本文介绍了如何在C#中捕获空/null字符串异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在使用文本框在窗口应用程序中输入名称.我想将此设为必填字段.如果文本框为空,如何捕获异常.
谢谢,
Jyoti Bhatnagar

Hi,
I am using a textbox to input a name in a window application. I want to make this a required field. How do I catch the exception if the textbox is left blank.
Thanks,
Jyoti Bhatnagar

推荐答案

如果TextBox为空,也不例外-您必须亲自检查它,通常在LostFocus事件中或在按下按钮时或类似的操作.
There is no exception if a TextBox is left blank - you have to check for it yourself, normally either in the LostFocus event, or on a button press or similar action.


空输入也不例外.这是输入验证的问题.我想您的输入字段默认为空,但是您想在特定事件上验证表单.让我们假设单击按钮.
您有几种方法可以做到这一点,但从这些文章开始:
http://www.devx.com/dotnet/Article/33506 [验证Windows窗体中的用户输入 [ Windows窗体的验证程序-ValidationProvider控件 [
Empty input is not an exception. It is a matter of input validation. I suppose your input field is empty by default, but you want to validate the form on a specific event. Let''s suppose on a button click.
You have several ways to do that, but start with these articles:
http://www.devx.com/dotnet/Article/33506[^]
Validate user input in Windows Forms[^]
Validators for Windows Forms - ValidationProvider Control[^]


您可以使用以下条件检查文本框是否为空,

if(String.IsNullOrEmpty(txtYourTextbox.Text))
{
//如果文本框为空,则可以使用MessageBox显示正确的消息
MessageBox.Show(请在文本框中输入值","TextboxLabel为必需",MessageBoxButtons.OK,MessageBoxIcon.Information);
}


希望这能解决您的问题.

谢谢,
Sanjeev Choudhary
Hi you can use following condition to check if text box is empty,

if(String.IsNullOrEmpty(txtYourTextbox.Text))
{
//if textbox is empty, you can show proper message using MessageBox
MessageBox.Show("Please enter value in text box", "TextboxLabel is Required", MessageBoxButtons.OK, MessageBoxIcon.Information);
}


Hope this solves your problem.

Thanks,
Sanjeev Choudhary


这篇关于如何在C#中捕获空/null字符串异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆