[英]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
I have four text box in C# ,If the value of any text box is :empty string,then it must be assigned as '0'.I have tried the following code which seems to be lenghty . 我在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";
}
Is there any more efficient code than the above one? 是否有比以上代码更有效的代码?
Rather than repeat yourself, create a new method to handle it: 与其重复自己,不如创建一个新方法来处理它:
private void SetEmptyTextBoxToZero(TextBox textBox)
{
if (textBox != null && string.IsNullOrEmpty(textBox.Text)
{
textBox.Text = "0";
}
}
Then you replace your code with: 然后,将代码替换为:
SetEmptyTextBoxToZero(txtReset1);
SetEmptyTextBoxToZero(txtReset2);
SetEmptyTextBoxToZero(txtReset3);
SetEmptyTextBoxToZero(txtReset4);
As " Binkan Salaryman" suggests, if you have lots of text boxes that need to be handled this way, then you can store references to them in a list and then iterate over them, rather than listing them out as above: 正如“ 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.