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 .
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:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.