You can do this in several ways, I will list them in the most recommended order for the least recommendable:
1. Delimiting the maximum size of the TextBox
You can change the MaxLength
property of the TextBox
component to receive at most 30 characters.
2. Let the user enter everything and warn you that it has passed the limit
In this case, you only need to do a normal validation using the .Length
property of string
. Ex.:
if(textBox.Text.Length > 30)
{
MessageBox.Show("Campo endereço estourou o limite de caracteres");
return;
}
3. Let the user type everything and cut a piece of information
I would not do it, not at all. It's a bad practice.
string endereco = textBox.Text.Length > 30 ? textBox.Text.Substring(0, 30) : textBox.Text;
Edit:
I just misunderstood your question. If you just want to limit a field that comes from some data source to 30 characters, the correct one is to use the Substring()
" of string
. This method receives two parameters of type int
. The first one defines the position of the first character to be "trimmed" (remember that positions start counting from zero), the second parameter is quantity characters that should be "trimmed."
See an example:
var enderecoCompleto = db.BuscarEnderecoCliente(); //endereço vindo do banco
string endereco = enderecoCompleto.Length > 30
? enderecoCompleto.Substring(0, 30) //comece no caracter 0 e pegue 30 caracteres
: enderecoDoBanco;