user9914768
user9914768

Reputation:

How to Constraint on TextBox in C#?

I try constraint for TextBox in C#. I succesfull this for users can put only numbers:

private void TxtID_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);          
    }

Now, I wonder how can users just write 11 char in TextBox? I try char.Max or Min but i can't in the KeyPress event.

Upvotes: 0

Views: 687

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

Something like this:

  public MyForm() 
  {
    InitializeComponent();

    // At most 11 characters
    TxtID.MaxLength = 11;
  }

  private void TxtID_KeyPress(object sender, KeyPressEventArgs e)
  {
    // char.IsDigit is too wide: it returns true on any unicode digit (e.g. Persian ones)
    e.Handled = (e.KeyChar < '0' || e.KeyChar > '9') && !char.IsControl(e.KeyChar);          
  }

  // On Paste we should validate the input:
  // what if user copy "bla-bla-bla 1234" and paste it to TxtID?
  private void TxtID_TextChanged(object sender, EventArgs e) 
  {
    Control ctrl = (sender as Control);

    string value = string.Concat(ctrl
      .Text
      .Where(c => c >= '0' && c <= '9'));

    if (value != ctrl.Text)
      ctrl.Text = value;
  }

Upvotes: 1

Related Questions