new programmer question

  • Thread starter Thread starter Ernest Griffin
  • Start date Start date
E

Ernest Griffin

I am teaching myself C# and was trying to build a small calculator. I
am trying to validate the process of ensuring that Integer keys are
pressed. I thought that I was able to capture the appropriate place for
intercepting the key press event and parse the result to determine which
key was pressed but I am removing the key prior to it showing up in the
text box. I have attached the code so you can see.

Ernie

private void txtCalculate_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
try
{
Int32.Parse(e.KeyChar.ToString());
}
catch
{
MessageBox.Show("Please enter Valid Numbers");
txtCalculate.Text=txtCalculate.Text.Substring(1,
txtCalculate.Text.Length-1);
}

}
 
Ernest Griffin said:
I am teaching myself C# and was trying to build a small calculator. I
am trying to validate the process of ensuring that Integer keys are
pressed. I thought that I was able to capture the appropriate place for
intercepting the key press event and parse the result to determine which
key was pressed but I am removing the key prior to it showing up in the
text box. I have attached the code so you can see.

Ernie

<snipped code>

I don't know if there would be a better way of doing this, but this
works:

private void textBox1_KeyPress(...)
{
char KeyChar = e.KeyChar;
e.Handled = KeyChar < '0' || KeyChar > '9';
}

Now, setting e.Handled to true causes the character pressed to not be
displayed in the text box. Setting it to false causes the character
to be displayed.
 
Back
Top