Get specific amount of characters from a textbox

3

I'm trying to get a specific amount of characters typed into a texbox, the current code is as follows:

novaconfiguracao.CupomEstabelecimento = tb_NomeFantasia.Text.Substring(0,48).ToString();

In case of typing less than 48 or more than 48 get caught up to 48.

    
asked by anonymous 05.12.2014 / 18:58

1 answer

6

You need to get the lowest of the two. Or the 48 or string size. If you try to get 48 characters and string is less than this it will give an index error.

It will look like this:

novaconfiguracao.CupomEstabelecimento = 
              tb_NomeFantasia.Text.Substring(0, Math.Min(tb_NomeFantasia.Text.Length, 48));

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

I did not understand this ToString() that you had placed.

    
05.12.2014 / 19:11