本文介绍了使用 C# 函数检查空文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个函数来检查表单上的任何文本框是否为空白.如果我将它添加到 TextBox 'leave' 事件,它目前可以工作.
I have written a function to check if any textboxes on a form are blank.It currently works if I add it to the TextBox 'leave' event.
我尝试将其添加到按钮点击事件中,但出现错误(NullReferenceException unhandled
).
I tried adding it to a button click event but it gives an error (NullReferenceException unhandled
).
代码如下:
public void inputBlank(object sender, EventArgs e)
{
TextBox userInput;
userInput = sender as TextBox;
userTextBox = userInput.Text;
string blankBoxName = userInput.Name;
string blankBox = blankBoxName.Remove(0,3);
if (userTextBox == "")
{
errWarning.SetError(userInput, "Please enter a value for " + blankBox);
userInput.Focus();
}
else
{
errWarning.SetError(userInput, "");
}
}
只是想知道您是否可以建议我如何修复它.
Just wondering if you could advise me how to fix it.
非常感谢.
推荐答案
您想验证 Windows 应用程序中的空文本框吗?最好在验证/验证事件中使用它.
You want to validate an empty textbox in Windows application? Better to use it in Validating / Validate event.
private void sampleTextbox8_Validating(object sender, CancelEventArgs e)
{
TextBox textbox = sender as TextBox;
e.Cancel = string.IsNullOrWhiteSpace(textbox.Text);
errorProvider1.SetError(textbox, "String cannot be empty");
}
private void sampleTextbox8_Validated(object sender, EventArgs e)
{
TextBox textbox = sender as TextBox;
errorProvider1.SetError(textbox, string.Empty);
}
这些链接可能对您有所帮助
These links may help you
这篇关于使用 C# 函数检查空文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!