使用C#函数检查空文本框

a.b*_*ell 2 c# validation textbox

我编写了一个函数来检查表单上的任何文本框是否为空.如果我将它添加到TextBox'leave'事件,它目前有效.

我尝试将其添加到按钮单击事件但它给出了一个错误(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, "");
        }
    }
Run Code Online (Sandbox Code Playgroud)

只是想知道你是否可以建议我如何解决它.

非常感谢.

Anu*_*raj 5

您想验证Windows应用程序中的空文本框吗?最好在验证/验证事件中使用它.

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);
}
Run Code Online (Sandbox Code Playgroud)

这些链接可以帮助您

  1. 验证WinForms TextBox(在C#中)
  2. WinForm UI验证