You can do this in several ways, I will list them in the order of the most recommended for less recommendable:
1. Delimiting the maximum Textbox size
You can change the property MaxLength
of the component TextBox
to receive at most 30 characters.
2. Let the user type everything and let him know that he has crossed the limit
In this case, you just need to do a normal validation using the property .Length
of string
. Ex.:
if(textBox.Text.Length > 30)
{
MessageBox.Show("Campo endereço estourou o limite de caracteres");
return;
}
3. Let the user type all and cut a piece of information
I wouldn’t do that, no way. It’s 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 is to use the method Substring()
of string
. This method takes two parameters of type int
. The first defines which the position of the first character to be "cropped" (remember that the positions start from scratch), the second parameter is the amount of characters to be "cut out".
Take 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;
What are you using? Windows Forms, WPF, etc?
– Randrade
try searching for Maxleng
– Tozzi
I’m using Windowsforms with c#
– Joelias Andrade
This varies if you are using Winforms, WPF or MVC, for example. It also varies whether you intend to cut out a piece of information or tell the user which character limit has popped.
– Jéf Bueno
In reality I am generating a txt file where the columns will be fixed. So if I delimit the field, whatever size comes from the BD, it will load the data even truncated, since the columns have to be fixed.
– Joelias Andrade