Limit the number of characters in a textbox

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 the 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 the buttons the maximum size of the textbox is ignored by the buttons, which add text infinitely, but not when use the computer keyboard. Is there any way to resolve this?

Here is an example of the code I'm using and a print of how my form is currently:

 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";
    }

    
asked by anonymous 22.09.2018 / 04:12

2 answers

3

Do the check in the insert itself.

By the way, a tip: if you're going to do exactly the same thing on all the buttons just by changing the text, you can just set the Tag property of each button as its number and use only a 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();
} 
    
22.09.2018 / 16:38
0

Hello, you just have to check if the size has exceeded the limit, if you exceeded it, then you 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;
   } 
    
22.09.2018 / 16:48