如果else语句文本框错误

本文关键字:错误 文本 语句 else 如果 | 更新日期: 2023-09-27 18:15:17

我试图创建一个if else语句来显示一个消息框,如果没有输入。

If(textbox1.text==false)
{
   messagebox.show("please fill in the boxes")
}

我有16个不同的文本框目前出来,我需要使用一个if else语句为每个?

如果else语句文本框错误

传递列表中的所有TextBoxes并循环

//Create list once in the constructor of main form or window
List<TextBox> list = new List<TextBox>()
//...
list.Add(textbox1);
list.Add(textbox2);'
//...
Then loop it
foreach(TextBox txt in list)
{
    if(String.IsNullOrWhiteSpace(txt.Text))
    {
        messagebox.Show("please fill in the boxes");
        break;
    }
}


如果所有文本框只需要数字/双输入,则使用TryParse检查value是否有效

foreach(TextBox txt in list)
{
    Double temp;
    if(Double.TryParse(txt.Text, temp) == true)
    {
        //save or use valid value 
        Debug.Print(temp.ToString());
    }
    else
    {
        messagebox.Show("please fill in the boxes");
        break;
    }
}

不能比较字符串和布尔值。文本框。Text是字符串数据类型。试试这个,如果你想为不同的文本框显示不同的消息,你必须对所有的文本框使用if-else语句。

If(textbox1.text=="")
{
messagebox.show("please fill in the boxes")
}

If(string.IsNullOrEmpty(textbox1.text) == true)
{
    messagebox.show("please fill in the boxes")
}

multiple textbox验证

在表单构造函数中使用foreach循环可以很容易地将处理程序添加到文本框中:

foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
    tb.Validating += textBox_Validating;
}

使用validating事件处理

private void textBox_Validating(object sender, CancelEventArgs e)
{
    TextBox currenttb = (TextBox)sender;
    if(currenttb.Text == "")
        MessageBox.Show(string.Format("Empty field {0 }",currenttb.Name.Substring(3)));
        e.Cancel = true;
    else
    {
        e.Cancel = false;
    }
}

字符串和布尔值是不可比较的,你也可以检查是否所有的文本字段都是空的,就像这篇文章中描述的

if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)) {
    //Textfield is empty
}

首先,您的问题中有一个类型不匹配错误。TextBoxText属性为string类型,关键字falsebool类型。你可以在这里阅读更多关于类型的内容。解决这个问题的方法是:

If (!string.IsNullOrEmpty(textbox1.Text))
{
    Messagebox.Show("please fill in the boxes")
}

其次,现代编程都是关于DRY原则。因此,答案是不是,您不需要为它们每个都编写相同的代码。

实际上至少有两种方法。第一种方法是创建文本框的某种集合(例如,一个数组)。然后创建一个方法来遍历这个集合,如下所示:

private bool AllTextboxesAreFilled()
{
    var textboxes = new TextBox[] { textBox1, textBox2, textBox3 };
    return textboxes.All(textbox => !string.IsNullOrEmpty(textbox.Text));
}

然后命名为:

if (!AllTextboxesAreFilled())
{
    MessageBox.Show("please fill in the boxes");
}

第二种方法是使这些文本框成为某个控件的子控件(例如Panel),然后遍历这些子控件。这样,您就不需要创建一个额外的集合(并且要记住在其中添加元素,以防您需要更多的文本框):

private bool AllTextboxesAreFilled()
{
    return holderPanel.Controls.OfType<TextBox>().All(textbox => !string.IsNullOrEmpty(textbox.Text));
}

用法与前面的示例相同。