开发者

Advice on checking if inputs are empty (.NET)

In my form, I have 8 textboxes. All of these need to be filled in, and I wanted to ch开发者_如何学JAVAeck if they are filled in before going to run the rest of the code.

The only way I've done it thus far is 8 nested IF statements, and this looks unorganised and seems like a horrible way to do it.

Can someone tell me a better way to do this? If there is one, of course.

Thanks :)


Is this winforms or webforms?

If Winforms, look at the ErrorProvider control.
If Webforms, look at the validation controls (specifcally, RequiredFieldValidator).

In either case, I would likely create a custom control that wraps the validation together with the textbox that you can just drop on your form where you need it.


Hmm, how about grouping the 8 textboxes into 1 Panel and looping through each of them instead? Something like this:

bool text = true;

foreach(Control ctrl in Panel)
{
    TextBox textbox = ctrl as TextBox;
        if (box.Text.Length == 0)
        {
            DisplayErrorMsg();
            text = false;
        }
}

if(text) ExecuteCode();


At form load time, make a collection of all the textboxes that cannot be empty. Then simply loop through them. This is similar to @Kronon answer, but without the Panel. I like changing the background color to indicate which fields should not be empty.

public partial class MainForm
{
    private List<TextBox> mandatoryTextBoxes;

    private void MainForm_Load(object sender, EventArgs e) {
        mandatoryTextBoxes = new List<TextBox>();
        mandatoryTextBoxes.Add(this.textBox1);
        // add other textboxes1
    }

    private bool CheckMandatoryFields() {
        bool allFieldsPresent = true;
        foreach (TextBox tb in this.mandatoryTextBoxes) {
            if (tb.Text.Length == 0) {
                tb.BackColor = Color.Yellow;
                allFieldsPresent = false;
            } else {
                tb.BackColor = Color.White;
            }
        }
        return allFieldsPresent;
    }

    private void DoWork() {
        if (!this.CheckMandatoryFields()) {
            this.SetError("Indicated fields cannot be empty");
            return;
        }
        // do real work here
    }
}


Simply use RequiredFieldValidator along with the ValidatorSummary field to display the validation messages.

Let me know if that helps.

Pratik

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜