c# – Get specific amount of characters from a textbox

Question:

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

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

In the independent case of being typed less than 48 or more than 48, get a maximum of 48.

Answer:

You need to take the lower value of the two. Or the 48 or string length. Trying to get 48 characters and the string is shorter than this will give an index error.

It will be like this:

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

See working on ideone . And in .NET Fiddle . Also posted on GitHub for future reference .

I didn't understand this ToString() you had put.

Scroll to Top