Limit the number of characters in a textbox

Asked

Viewed 691 times

1

I am simulating an electronic urn in C#. To limit data entry, I decided to create a "keyboard" from 0 to 9, for the insertion of votes. However, I’m having trouble limiting the amount of characters in the textbox, even setting the maximum size to 2 characters, for example, when using buttons the maximum size of the textbox is ignored by buttons, which add text infinitely, The same doesn’t happen when I use the computer keyboard. Is there any way to fix this?

Here’s an example of the code I’m using and a print of what my form looks like at the moment:

 private void btnUm_Click(object sender, EventArgs e)
    { 
        txtNum.Text +=  "1";

    }

    private void btnDois_Click(object sender, EventArgs e)
    {
        txtNum.Text+="2";
    }

    private void btnTres_Click(object sender, EventArgs e)
    {
        txtNum.Text += "3";
    }

    private void btnQuatro_Click(object sender, EventArgs e)
    {
        txtNum.Text += "4";
    }

    private void btnCinco_Click(object sender, EventArgs e)
    {
        txtNum.Text += "5";
    }

    private void btnSeis_Click(object sender, EventArgs e)
    {
        txtNum.Text += "6";
    }

    private void btnSete_Click(object sender, EventArgs e)
    {
        txtNum.Text += "7";
    }

    private void btnOito_Click(object sender, EventArgs e)
    {
        txtNum.Text += "8";
    }

    private void btnNove_Click(object sender, EventArgs e)
    {
        txtNum.Text += "9";
    }

    private void btnZero_Click(object sender, EventArgs e)
    {
        txtNum.Text += "0";
    }

inserir a descrição da imagem aqui

  • You can use the event TextBox_textChanged, so whenever a digit is inserted in the textBox you do the size check.

2 answers

3


Check on the insertion itself.

Incidentally, a tip: if you are going to do exactly the same thing on all buttons just by changing the text, it is possible to just set the property Tag of each button as its number and use only one click event.

So you focus logic on just one place and avoid this whole repetition.

See example:

private void botaoUrna_Click(object sender, EventArgs e)
{
    const int TamanhoMaximo = 2;

    var bt = (Button)sender;

    if(txtNum.Length < TamanhoMaximo)
        txtNum.Text += bt.Tag.ToString();
} 
  • It’s much simpler now thanks to this tag tip. Thank you very much!

0

Hello, just check if the size has exceeded the limit, if you have exceeded then will not add the word. item

Follow the example :

  private void botaoUrna_Click(object sender, EventArgs e)
  {
    const int TamanhoMaximo = 12;

    var bt = (Button)sender;

    if(txtNum.Length > TamanhoMaximo)
       return;
   } 

Browser other questions tagged

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