This post is very much a combination of my three previous posts (Silverlight QueryString using TryParse() method, Validate GUID in Silverlight – Parse GUID in C# and Extension methods in Silverlight and C#) to demonstrate all these great features in one place. I have also added an Extension method in this project to validate Date and Time using a simple Regular Expression, for better validation I suggest change the Regular Expression to match your specific needs.
I am not explaining the code for this project as each part is explained in details in the posts I mentioned above, but please do feel free to ask any questions in the comment section below and I will try to answer as soon as I can.
This project can be downloaded from CodePlex from here, and feel free to play with the working version of it below.
In order to get the value of your QueryString parameters from the URL all you need is this line of code:
int id = HtmlPage.Document.QueryString["ID"];
And you need to add Windows.Browser namespace for HtmlPage class:
However, there are always two situations which could break your application:
- if there are no “ID” parameters in the url
- if there is an “ID” parameter in the url, but it has a string value instead of an integer number.
To avoid breaking the code and causing runtime error we need to add a few conditions and also parse the value to integer instead of assigning it right away. We can use Int32.TryParse() method to test the value which we are about to assign to an integer variable before we actually do so, this way we will only assign it if it really is an integer:
int id = -1;
string queryStringValue = HtmlPage.Document.QueryString["ID"];
if (Int32.TryParse(queryStringValue, out id))
// the result was successful and
// the correct ID will be inserted to id
// the result was not successful
Using above method, you ensure the id gets assigned a value only if the ID parameter in the url has a valid integer value, or it will remain as -1 if the value was not an integer.