How to do an if-type validation in a set of options?

-1

I need to make a if where I check a set of options to not make a if inside another if to check if a field is filled or not, I want to do it with a single if . Ex if(valr1, valor2, valor3 != "")

Follow the code

DataSet ds = new DataSet();

ds.ReadXml(@"\192.168.0.251\Geral_G.M\Expedicao\XML_ENTRADA\" + txt_chave.Text + ".xml");

txt_fornecedor.Text   = ds.Tables["emit"].Rows[0]["xNome"].ToString();
txt_cnpj.Text         = ds.Tables["emit"].Rows[0]["CNPJ"].ToString();
txt_nota.Text         = ds.Tables["ide"].Rows[0]["nNF"].ToString();
txt_ie.Text           = ds.Tables["emit"].Rows[0]["IE"].ToString();
emissao               = Convert.ToDateTime(ds.Tables["ide"].Rows[0]["dhEmi"]);
saida                 = Convert.ToDateTime(ds.Tables["ide"].Rows[0]["dhSaiEnt"]);

txt_emissao.Text      = Convert.ToString(emissao);
txt_saida.Text        = Convert.ToString(saida);
    
asked by anonymous 29.07.2018 / 15:43

2 answers

2

In your case I suggest that you would create a class with the fields that represent that XML and use DataAnnotations for properties that can not be empty, would be the Required attribute, see:

[Required(ErrorMessage = "Nome é obrigatório.")]
public string Nome {get; set;}

It is a good alternative for validating objects, you can even implement the IValidatableObject interface on the object to be validated.

Using a list

If you want to check multiple values at once, you can use a list for this:

var valores = new List<string>{ "Hi", "casa", "Teste", "ga", "     sa ", null}; 

In the Exists method you specify the predicate with the condition, which would be:

v => string.IsNullOrWhiteSpace(v)

To check if there are any nulls in the range of values null , empty "" or whitespace " " .

See the complete code:

using static System.Console;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {               
        var valores = new List<string>{ "Hi", "casa", "Teste", "ga", "     sa ", null}; 
        var algumElementoVazioOuNulo = valores.Exists(v => string.IsNullOrWhiteSpace(v));
        if (algumElementoVazioOuNulo)
        {
            WriteLine("Sim");   
        }               
        else 
        {
            WriteLine("Nao");
        }
    }
}

See working at .NET Fiddle .

Learn more at documentation .

    
29.07.2018 / 17:28
1

You can use the & & (e) or || (or) , but you still have to do the individual verification of each item. You can try something like:

if(val1 != "" && val2 != "" && val3 != ""){ ... }

Dai just follow the truth table

    
29.07.2018 / 15:53