Picking specific amount of characters from a textbox

Asked

Viewed 1,801 times

4

I am trying to get a specific amount of typed characters in a texbox, the current code is as follows:

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

In the case of being typed less than 48 or more than 48 pick up maximum 48.

  • 1

    And what is the doubt? You’re already doing what you say you want.

  • The problem is you’re making a mistake

  • 1

    @Brunorodrigues complete the question with all relevant details, please. Suggested reading: [Ask].

1 answer

7


You need to take the lower value of the two. Either the 48 or the size of the string. If you try to take 48 characters and a string is less than this will give an index error.

Will it be so:

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I didn’t get that ToString() that you had placed.

Browser other questions tagged

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