繁体   English   中英

如何验证四个文本框的值是否为空字符串,以及如何使用最少的代码在C#中将这些文本框分配为“ 0”值(如果在C#中为空)

[英]How to validate if the values of four text box is empty string or not and assign these text box as “0” value if it is empty in C# with minimal code

我在C#中有四个文本框,如果任何文本框的值是:empty string,则必须将其指定为“ 0”。我尝试了以下似乎冗长的代码。

                if (txtReset1.Text == "")
                {
                    txtReset1.Text = "0";
                }

                if (txtReset2.Text == "")
                {
                    txtReset2.Text = "0";
                }

                if (txtReset3.Text == "")
                {
                    txtReset3.Text = "0";
                }

                if (txtReset4.Text == "")
                {
                    txtReset4.Text = "0";
                }

是否有比以上代码更有效的代码?

与其重复自己,不如创建一个新方法来处理它:

private void SetEmptyTextBoxToZero(TextBox textBox)
{
    if (textBox != null && string.IsNullOrEmpty(textBox.Text)
    {
        textBox.Text = "0";
    }
}

然后,将代码替换为:

SetEmptyTextBoxToZero(txtReset1);
SetEmptyTextBoxToZero(txtReset2);
SetEmptyTextBoxToZero(txtReset3);
SetEmptyTextBoxToZero(txtReset4);

正如“ Binkan Salaryman”建议的那样,如果您有很多需要以这种方式处理的文本框,则可以将对它们的引用存储在列表中,然后对其进行迭代,而不是像上面那样列出它们:

var textBoxes = new List<TextBox> { txtReset1, txtReset2, txtReset3, txtReset4 };

...

// Option 1: using .ForEach()
textBoxes.ForEach(tb => SetEmptyTextBoxToZero(tb));

// Option 2: using foreach
foreach (var tb in textBoxes)
{
    SetEmptyTextBoxToZero(tb);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM