IsDateTime C# ErrorProvider
Section: WinFormsRating: Not rated yet!

Add to YiGGAdd to google-bookmarksAdd to linkarenaAdd to redditAdd to del.icio.usAdd to misterwongAdd to digg




Introduction

In this sample-snippet the author shows how to check if an input-value is of type DateTime. The method is provided in a static class called TypeHelper. In the example, the class is used to show the occured error in a WinForms-ErrorProvider.

public static class TypeHelper { /// <summary> /// Check if an input-value is of type DateTime /// </summary> /// <param name="value">input</param> /// <returns>bool</returns> public static bool IsDateTime(object value) { try { if (value == null) return false; DateTime dateTime = DateTime.Parse(value.ToString()); return true; } catch (FormatException) { return false; } } }

The TypeHelper is used to display the error like that:

public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnIsDateTime_Click(object sender, EventArgs e) { if (!TypeHelper.IsDateTime(textBox1.Text.Trim())) errorProvider1.SetError(textBox1, "You did not enter a valid DateTime-type"); else errorProvider1.SetError(textBox1, ""); } }

And this is how the result looks like:


Figure 1

It's an easy example but you can extend it with other methods like IsNumeric... Have fun!




 Reader-Comments: