1

The plot is this - I have a Save() method which calls a validation method withing itself and I want to be sure that if the validation method caught an error, the execution of the Save() method will be stopped. What I've done is making a bool method for the validation:

protected virtual bool IsNullOrEmptyControl(params Control[] controls) { bool validationFlag = false; foreach (Control ctrl in controls) { if (string.IsNullOrWhiteSpace(ctrl.Text)) { ctrl.BackColor = System.Drawing.Color.Yellow; if (validationFlag == false) { ctrl.Focus(); validationFlag = true; } } } if (validationFlag == true) { MessageBox.Show("The fields in yellow could not be empty", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } 

And calling it from withing my Save() method:

public bool Save() { some code... IsNullOrEmptyControl(txtClientCode, txtClientName); some code.. clientService.Save(entity); } 

I thought that because my IsNullOrEmptyControl() method is bool if it returns false then this will mean stop of further code execution in Save() but it seems I was wrong. So what's the right way to do this?

4 Answers 4

1

IsNullOrEmptyControl method just returns the value. You should check this value in our code and react to it

bool checkResult = IsNullOrEmptyControl(txtClientCode, txtClientName); if(checkResult == false) { return false; } some code.. clientService.Save(entity); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It seems that this is the most harmless way to deal with this.
0

You should create an if statementaround your save call. If the IsNullOrEmptyControl returns false the clientService.Save(entity); will not be executed.

public bool Save() { //some code... if(IsNullOrEmptyControl(txtClientCode, txtClientName)) { //some code.. clientService.Save(entity); } } 

Comments

0

You should really be assigning the return value of your validation method to a variable and check it before calling clientService.Save().

Also you may want to put a break in the foreach loop above, just below the line where you set your flag to true.

1 Comment

No, I want to mark all fields that don't match the validation rule with yellow, but I want the focus to stay on the first found. That's way I raise the flag but keep on checking.
0

I think that the code should be:

public bool Save() { some code... if(IsNullOrEmptyControl(txtClientCode, txtClientName)) { some code.. clientService.Save(entity); } } 

1 Comment

I would like to leave the method call within the function, otherwise i will need to make a lot of changes. Isn't there another way?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.