Search code examples
c#messagebox

Data validation and list of errors within one message box c#


Hope you all well. I would like to ask you for an advise.

I am looking for a way to validate a data before OnClick button gets executed. I do have few ComboBoxes with some data to choose from. Currently I have used some solution, which does look quite "dirty" and I am not happy about it.

Currently I am using something similar to this:

if(box1 == null)
{
   MessageBox.Show("Error 1");
}
if(box2 == null)
{
   MessageBox.Show("Error 2");
}
if(box3 == null)
{
   MessageBox.Show("Error 3");
}

If I am having 3 fields empty I will get message displayed 3 times one for each error. Is there a way to list all errors within one message box if error is true?

I was thinking of something like this:

bool a = true;
bool b = true;
bool c = true;

a = (box1 == null);
b = (box2 == null);
c = (box3 == null);

if(a || b || c)
{
  //Display list of errors where condition is true
}

I would highly appreciate any suggestions.

Many thanks in advance.


Solution

  • Something like this:

    var errors = new List<string>();
    if(box1 == null)
       errors.Add("Error 1");
    if(box2 == null)
       errors.Add("Error 2");
    if(box3 == null)
       errors.Add("Error 3");
    
    if (errors.Count > 0) 
       MessageBox.Show(string.Join(Environment.NewLine, errors));