gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:32:19 25 4
gpt4 key购买 nike

我编写了一个函数来检查表单上的文本框是否为空白。如果我将它添加到 TextBox 的“离开”事件中,它目前可以正常工作。

我尝试将它添加到按钮点击事件中,但它给出了一个错误(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, "");
}
}

只是想知道您是否可以建议我如何修复它。

非常感谢。

最佳答案

您想验证 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);
}

这些链接可能对您有帮助

  1. Validating WinForms TextBox (in C#)
  2. WinForm UI Validation

关于c# - 使用 C# 函数检查空文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5605669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com