Monday, March 28, 2005

Developing Windows Applications - III

Its very rare that one application doesnt take any input from user. Almost all application depends upon users input in some sort. In most application user enters information through user interface. Data validation ensures that all data entered by user falls under the acceptable reason. For example you asked user to give the time she worked. Here application has to validate that she should not give more than 24 hours. Even 24 hour is also non human but acceptable. Purpose of validating user data is to develop robust application and not to have any unexpected behavior at application or database level.

We can categorize validation in two categories.
1. Form-level validation
2. Field-level validation
Form level validation can be termed as where you require values in some fields must be provided. In such scenarioyou at least need some sort of values. From level validation is usually performed when user is about to submit her inputs. In case of field level validation you check for value whether it is under acceptable range or not.

Field-Level Validations
TextBox is much used control that is used to take user inputs. So the way it provides some properties to control user input in specific manner. Some of these properties include:
· MaxLength
· ReadOnly
· PasswordChar

MaxLength
This property lets you set the maximum number of character a textbox can take.

ReadOnly
If set this property makes a textbox to behave in non editable mode. A user would not be able to make any changes to content of textbox.

PasswordChar
Though not restricting user to some particular value, but useful because passwords are sensitive data and should be displayed in non readable mode. You can give any character as PasswordChar and when user types, her password will be non readable to others.

Using Events to perform Field-Level validations

KeyPress
This is an important event to track while performing field-level validation. This is event is fired when user presses a key that has corresponding ASCII value. This excludes special keys like CTRL, SHIFT, ALT, DEL, arrow keys etc.Rest all keys we can track in this event. KeyPressEventArgs is the type of event that is passed to the event handler of KeyPress. KeyPressEventArgs provides us KeyChar and Handled property. KeyChar contains the key that was pressed. If we set Handled property as true then that key will be treated as user has not pressed that key. Char class provides us methods perform some basic validation for each key that is pressed. These methods include:
· Char.IsNumber
· Char.IsDigit
· Char.IsPunctuation
· Char.IsLetter
We can perform validation as shown below:
private void textName_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{

if (char.IsNumber(e.KeyChar) || char.IsPunctuation(e.KeyChar))
{
//Dont pass it to textbox. Filter it here.
e.Handled = true;
}
}


The Validating and Validated Events
Easiest way to validate user data is to validate it in Validating event. Validating event occurs before control loses focus. This event is occurred when CausesValidation property of control that is about to receive the focus is set to true. To use Validating property CausesValidation of control to be validated should also be true. By default all controls have CausesValidation set to true while they are created in design mode.Validating event takes one parameter of type CancelEventArgs. It does have Cancel property. Set it to true, if you want to push the focus back to control for which validation is failed.
Validated event is fired when a control is successfully validated. Following is the way you can implement validating event:

private void textName_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (textName.Text.Equals(string.Empty))
{
e.Cancel =
true;
}
}


The code shown above will force user to enter at least one character in name field. Without entering some value user cant leave this textbox. Even user cant close current screen. Did you recall something at this point? Yes, we should not force user to behave in some particular manner. They would not like it. I have described Validating event for sake of completeness of this discussion, however in my humble opinion you should avoid Validating event as it forces user to enter data in a very rude manner.

Form-Level Validation
Form level validation is a way to implement validation for all input controls at once. To perform form level validation we can implement centralized procedure that will be consulted before user us about to go to next level. We can implement form level validation is following manner:

private bool ValidateData()
{
f
oreach (Control control in this.Controls)
{
if (control.Text.Equals(string.Empty) && control is System.Windows.Forms.TextBox)
{
MessageBox.Show("You can't leave " + control.AccessibleName + " empty",
"Validation Test");
if (control.CanFocus)
{
control.Focus();
}
return false;
}
}
return true;
}


To ensure, this code flags error message in correct sequence, you have to make sure that you added the controls to Forms.Control collection in a desired sequence. Otherwise it willflag the message for bottom most control in form before other controls.

The ErrorProvider Component

The ErrorProvidercomponent provides an easy way to communicate validation errors to your users. The ErrorProviderallows you to set an error message for each control on your form whenever the input is invalid. An error message produces an error icon next to the control, and error message text is shown as a Tool Tip whenthe mouse hovers over the affected control. The ErrorProvider component is found in the Windows Forms tab of the Toolbox.

Using ErrorProvider
Following are the steps to accommodate ErrorProvider:
1. Drag and drop ErrorProvider component in your form.
2. Call its SetError method, when validation is failed.

SetError method takes two parameters. First one is the control for which validation is failed. Using this value ErrorProvider will blink error icon next to the control. Second parameter is string value that will be shown when user hovers her mouse over blinking error icon. Following is the demonstration to accommodate ErrorProvider in code:

private void textName_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || char.IsPunctuation(e.KeyChar))
{
e.Handled =
true;
errorProvider.SetError(textName,
"Name can not have numbers or punctuation marks");
}
else
{
errorProvider.SetError(textName,
string.Empty);
}
}


When you feel that validation is successful, call SetError method with empty string. This will clear the blinking error icon. You can further customize ErrorProvider by setting BlinkRate and BlinkStyle properties of ErrorProvider control. These properties are self explanatory. Arent they? Using BlinkRate we can control the blink rate of ErrorProviders error icon.BlinkStyle will let you decide when to blink, when not to or not at all.

We have covered many aspects of windows applications however we feel that it is not even the tip of iceberg. But we are at the point from where you can take off. Better luck and all the best with .Net windows programming.

No comments: