Pages

Tuesday, July 28, 2009

Windows Forms Input Validation

ErrorProvider Control Validating Event

MaxLength property of TextBox can be used to restrict the input lenght of the textbox to specified number.
Validating Event is used to check for the validity of data in the event of loosing focus from the control.

In the following example the user can't navigate away from the control unless he enters some value in the text box.

Make sure you give a visual indication to the error stating the error. In this case I am using an ErrorProvider Control for this purpose.

private void txtName_Validating(object sender, CancelEventArgs e)
{
if (txtName.Text == "")
{
e.Cancel = true;
errorProvider1.SetError(txtName, "Name cannot be blank");
}
else
errorProvider1.SetError(txtName, "");
}














Checking for Float values using float.TryParse

private void textBox1_Validating(object sender, CancelEventArgs e)
{
float num1;
bool res = float.TryParse(textBox1.Text, out num1);
if (res == false)
{
errorProvider1.SetError(textBox1, "only float is accepted");
}
else
{
errorProvider1.SetError(textBox1, "");
}
}



KeyDown event to Check for special keys
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt == true)
MessageBox.Show("Alt key pressed");
else if (e.Shift == true)
MessageBox.Show("Shift key pressed");
else if(e.Control == true)
MessageBox.Show("Contol key pressed");
else if (e.KeyCode == Keys.F1)
MessageBox.Show("F1 pressed");
}

WPF TextBox KeyDown Event
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftShift)
MessageBox.Show("Left shift key");
else if (e.Key == Key.RightShift)
MessageBox.Show("Right shift key");
else if (e.Key == Key.RightCtrl)
MessageBox.Show("Right Ctrl key");
else if (e.Key == Key.F1)
MessageBox.Show("F1 Key pressed");
}

KeyPress Event to Discern Character Keys

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}

KeyPress Event to Discard Non numeric input

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (! char.IsNumber(e.KeyChar))
e.Handled = true;
}

Discarding Lower Case Character
private void txtGrade_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsLower(e.KeyChar))
e.Handled = true;
}

No comments:

Post a Comment