Mouad Raizada
Mouad Raizada

Reputation: 41

How I can bound a checkBox with KeyPress event of a textBox in C#

Hi I'm new in C# visual programming and I'm facing a problem in winform that is I want to make the textBox accepts numbers only when a checkBox is checked ... the problem is that I know how to use the code inside KeyPress event but it doesn't work with the idea of checkBox.

I have this code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
  if(char.IsLetter(e.Keychar))
  {
    e.Handled = true;
  }
}

Now the question is how to make this happens when a checkBox is checked???

Upvotes: 0

Views: 662

Answers (4)

Mouad Raizada
Mouad Raizada

Reputation: 41

Thanks to all of you ..

I wrote this code to enter numbers but only one dot '.' and it works finally ... thanks a lot for help

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (this.checkBox1.Checked)
        {
            e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }


        }
    }

Upvotes: 1

Eplzong
Eplzong

Reputation: 670

Simply try this in your TextBox's keypress event :

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {

            if(this.checkBox1.Checked)
            {
                //Allow only number
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
                {
                    e.Handled = true;
                }
            }            
        }

Upvotes: 0

Joe B
Joe B

Reputation: 788

Use the MaskedTextBox control and handle the checkbox event to change the mask property

 private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if(checkBox1.Checked == true)
        {
            maskedTextBox1.Mask = "000-000-0000";
        }
        else
        {
            maskedTextBox1.Mask = null;
        }
    }

Upvotes: 0

Kevin
Kevin

Reputation: 2631

on your key press event you could do:

if (this.checkBoxNumericOnly.Checked)
{
    //your code to only allow numerics...
}

Upvotes: 2

Related Questions