condition to prevent textbox null

Asked

Viewed 696 times

1

How do I make the system not allow insertion of null values inside a textbox, using id condition?

if(verificar se o textbox é null){
    MessangeBox.Show("digite um valor");
}
  • 3

    have tried if (!string.IsNullOrEmpty(IdTextoBox.Text)) ?

  • Ricardo, I hadn’t tried yet... but thanks worked!!

1 answer

5


You can check whether a value is null in several ways. After all, what you consider null?

We have to consider the difference between null and emptiness, or whitespace.

inserir a descrição da imagem aqui

Null is when a variable has no value assigned, that is, when it has never been "set". Thus, always a NullReferenceException (better known as Null Object Reference) is caused when you try to access a null object.

Emptiness is the default value of the type. For example, in a String, its default value is "", that is, empty, with no value inside. Therefore, it is not null, once it has a value in there, even though it is empty.

Whitespace is not any of the acimas, but any String with only invisible spaces and/or characters. You also enter the "Empty" category if you are looking for valid values.


Which one will I use?

In my view of your situation, use an own . NET Framework check known as String.IsNullOrWhiteSpace. This method will verify whether a String is Null, Empty or Whitespace.

if(String.IsNullOrWhiteSpace(textBox1.Text)) {
    MessangeBox.Show("digite um valor");
    return;  // isso faz com que você saia do método e não execute os próximos processamentos
}

So if your TextBox has empty value, null or only spaces, the warning message will be displayed and will soon exit the method.


If you want to use each method individually, both for the three elements above, do:

if(objeto == null) {
    // o objeto é nulo, não foi atribuído valor
} // ou objeto is null se a referência também for nula

if(objeto == "") {
    // o objeto não é nulo, mas é vazio
    // obs.: isso serve apenas para strings
}

if(string.IsNullOrWhiteSpace(objeto)) {
    // o objeto é nulo, vazio ou contém espaços em branco
    // obs.: isso serve apenas para strings
}
  • 2

    Very good, only the classic image was missing: https://i.stack.Imgur.com/j9vg8.jpg :-)

  • 1

    @hkotsubo Hahaha, exactly that. I added the image and credited you in the comments of the edition. xD

  • 1

    Haha dear, thank you so much for the explanation !!!!!! great reference Theme Vs. Image !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.