Wednesday, July 15, 2009

Simple way to validate DataTypes

The importance of data validation can never be ignored by any programmer since we can never trust users to enter data in proper format. While special controls like combo box,listbox etc limit the users to the options provided there comes always some need to place in text boxes.
There are many methods to make sure that the data entered is in proper format. For instance you have a MaskedTextBox control that provides pre-defined data formats to compare the user input with. Also you can always use the System.Text.RegularExpressions namespace to provide validation.
But why go into complexities of making strange looking expressions when you want to provide validation for really simple things? What if you want the user to enter some Float, DateTime or even Int values?
Thanks to the .Net framework we can manage such tasks easily by taking a different route or perhaps I should say a short cut.

Lets C . . .

Assuming that we have a TextBox control named text1 on our windows form and we want to allow input in only double/float format.

All we have to do is to place a few lines to the submit event of the form or any other event as per required:

public void SomeEvent(object sender, EventArgs e)
{
try
{

double.Parse(text1.Text);

}
catch
{
MessageBox.Show("Please provide a valid data. Only floating point numbers allowed.");
}
}

No comments:

Post a Comment