简体   繁体   中英

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 .

                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.

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