using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AspNetNormalIssue.Webform
{
public partial class DropDownListString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string userMeasurement = ViewState["DropDown"] as string;
if (userMeasurement == null && userMeasurement == "")
{
return;
}
}
catch (Exception)
{
return;
}
}
}
}
Result:
Best Regards,
Brando
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Thanks Brando, but I get an error because the userMeasurement appears in a switch statement after and if I use this solution then userMeasurement isn't recognised because it doesn't exist in the current context.
None
0 Points
3 Posts
How do I prevent the ViewState of a dropdown throwing an error if no option is selected?
Jul 03, 2018 08:08 AM|kevinfarrell2k|LINK
I tried put in try catch :
string userMeasurement = ViewState["DropDown"].ToString();
try
{
if (userMeasurement == null && userMeasurement == "")
{
showError("Please select a measurement type");
return;
}
}
catch(Exception)
{
showError(Please enter valid measurement;
return;
}
The first line with ViewState keeps throwing NullReferenceException even when I tried to wrap the String userMeasurement line in the try
Star
9831 Points
3120 Posts
Re: How do I prevent the ViewState of a dropdown throwing an error if no option is selected?
Jul 04, 2018 03:21 AM|Brando ZWZ|LINK
Hi kevinfarrell2k,
According to your description, I suggest you try to use as keywrod to aviod throwing the exception.
From MSDN article.
The as operator is like a cast operation. However, if the conversion isn't possible, asreturns null instead of raising an exception.
More details, you could refer to below demo codes:
ASPX:
Code-behind:
Result:
Best Regards,
Brando
None
0 Points
3 Posts
Re: How do I prevent the ViewState of a dropdown throwing an error if no option is selected?
Jul 04, 2018 08:16 AM|kevinfarrell2k|LINK
Thanks Brando, but I get an error because the userMeasurement appears in a switch statement after and if I use this solution then userMeasurement isn't recognised because it doesn't exist in the current context.
All-Star
54508 Points
14111 Posts
Re: How do I prevent the ViewState of a dropdown throwing an error if no option is selected?
Jul 04, 2018 06:16 PM|mudassarkhan|LINK
You don't need any Try Catch. Just use Convert.ToString() instead of ToString() function
Convert.ToString() will not throw error even if the object is NULL.
Blog: ASPSnippets | Forum: ASPForums | Company: Excelasoft