C# 用户未处理的KeyNotFoundException

C# 用户未处理的KeyNotFoundException,c#,xaml,query-string,code-behind,C#,Xaml,Query String,Code Behind,我试图在MainPage.xaml.cs中检索一个查询字符串值,但是还需要访问该值,并将其作为另一个页面(aspx)上的html ID访问。关键是,如果我试图在QueryString值不存在的情况下访问此代码,我会得到一个KeyNotFoundException 我试图通过以下方法来克服这个问题 HtmlDocument htmlDoc = HtmlPage.Document; if (htmlDoc.QueryString["productCode"] != null) { produ

我试图在MainPage.xaml.cs中检索一个查询字符串值,但是还需要访问该值,并将其作为另一个页面(aspx)上的html ID访问。关键是,如果我试图在QueryString值不存在的情况下访问此代码,我会得到一个KeyNotFoundException

我试图通过以下方法来克服这个问题

HtmlDocument htmlDoc = HtmlPage.Document;
if (htmlDoc.QueryString["productCode"] != null)
{
    productCode = htmlDoc.QueryString["productCode"].ToString();
}
else
{
   productCode = htmlDoc.GetElementById("vidWeeklyFeature").GetProperty("value").ToString();
}
但仍然得到同样的例外

如何根据该值是否可以作为查询字符串访问的条件检索该值


(很抱歉有点口齿不清)

您可以使用TryGetValue方法,而不是使用索引器

它看起来是这样的:

HtmlDocument htmlDoc = HtmlPage.Document;
string productCode;

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

在哪一行获得异常?如果(htmlDoc.QueryString[“productCode”!=null),您可以将其包装在try catchIn中