Search code examples
c#xamlquery-stringcode-behind

KeyNotFoundException unhandled by user


I am trying to retrieve a query string value inside my MainPage.xaml.cs and however also need to access this value accessing it as an html ID on a different page(aspx). Point is if I try to access this code where the QueryString value does not exist I get a KeyNotFoundException.

I have tried to overcome this problem by doing the following

HtmlDocument htmlDoc = HtmlPage.Document;
if (htmlDoc.QueryString["productCode"] != null)
{
    productCode = htmlDoc.QueryString["productCode"].ToString();
}
else
{
   productCode = htmlDoc.GetElementById("vidWeeklyFeature").GetProperty("value").ToString();
}

but still get the same Exception.

How can I retrieve this value based on the condition that the value can be accessed as a QueryString or not?

(Sorry for being a bit inarticulate)


Solution

  • You can use the TryGetValue method rather than to use the indexer.

    It would look like this:

    HtmlDocument htmlDoc = HtmlPage.Document;
    string productCode;
    
    if (!htmlDoc.QueryString.TryGetValue("productCode", out productCode))
    {
        productCode = htmlDoc.GetElementById("vidWeeklyFeature").GetProperty("value").ToString();
    }