Ask to fill in a field c #

0

Well, what happens next I'm trying to ask for a field in case it's blank

I have the following, I have a textbox with name txtEdad

then I put it like that

int edad=Int32.Parse(txtEdad.Text);

if(txtEdad.Text=="")
{
  MessageBox.Show("Debes rellenar este campo");
}

But when I try it and leave the Age field blank, it sends me to this line and does not show the message in other words "It stops and sends me to that line"

int edad=Int32.Parse(txtEdad.Text);
    
asked by user90058 23.09.2018 в 22:21
source

2 answers

2

This happens because in this instruction

int edad=Int32.Parse(txtEdad.Text);

You are trying to convert an empty string into a number. To what number is equal the string "" you guessed! to none, that's why it throws the exception and the program breaks.

if(string.IsNullOrWhiteSpace(txtEdad.Text))
{
  MessageBox.Show("Debes rellenar este campo");
}
else
{
  int edad=Int32.Parse(txtEdad.Text);
}

And for this case I would also recommend you use int.TryParse instead of int.Parse .

    
answered by 23.09.2018 в 23:09
0

If you try to convert a string into numeric you must validate that the string can actually be converted into numerical something that does not happen with a vacuum or alphanumeric. The best option is to use the function TryParse that will return a Boolean and also if you can convert the string into number you will assign the value to the variable.

With this method you can play with the validations:

int edad = 0;
if (!int.TryParse(txtEdad.Text, out edad))
    MessageBox.Show("Campo Edad inválido por favor ajuste y vuelva a intentar");
    
answered by 24.09.2018 в 18:30