How to delimit a string fields in C #

5

I have a string field for example address in code. This address field receives a 60 character die.

What I want is to delimit the address size so that it only receives 30 characters and not above that, even if it truncates the information.

Is it possible?

    
asked by anonymous 24.02.2016 / 14:23

2 answers

5

You probably want something that truncates the message.

const int MaxTamanhoEndereco = 30;

var endereco = "Rua dos Bobos, número Zero";
if (endereco .Length > MaxTamanhoEndereco )
    endereco = endereco .Substring(0, MaxTamanhoEndereco ); 
    
24.02.2016 / 14:28
3

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;
    
24.02.2016 / 14:37