Silverlight Tips provides simple and useful tutorials and tips with real life examples, live demos and sample codes to download.
About authors:
Damon Serji
Damon Serji,
Silverlight developer working at Metia in London.
Gavin Wignall
Gavin Wignall,
Interactive Design Lead, working in design for over 10 years, the last 3 being in Silverlight.
Allan Muller
Allan Muller,
Developer, working on various types of Silverlight and WCF projects.

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.

Get Microsoft Silverlight
Posted by Damon Serji on 7. October 2009 18:57 under: Intermediate
 with 1 Comments

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:

using System.Windows.Browser;

However, there are always two situations which could break your application:

  1. if there are no “ID” parameters in the url
  2. 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;
if (HtmlPage.Document.QueryString.ContainsKey("ID"))
{
    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
    }
    else
    {
        // 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.

Posted by Damon Serji on 30. September 2009 22:30 under: Basic, Intermediate
 with 3 Comments