Error: Unable to cast object of type 'System.I

2019-02-28 17:33发布

I have finish perfectly coding Register Page, Login and now the UpdateCustomer page has errors - Background info : I'm using Microsoft Access as data source

    LabelState.Text = (string)Session["sState"];
    LabelPostalCode.Text = (string)Session["sPostalCode"];
    LabelContactNumber.Text = (string)Session["sContactNumber"];
    LabelEmail.Text = (string)Session["sEmail"];
    LabelPassword.Text = (string)Session["sPassword"];

Everything here is fine except LabelContactNumber.Text = (string)Session["sContactNumber"].

I believe it is because only ContactNumber in Access is set as Int the rest is Text therefore there's no error when I use (string).

3条回答
▲ chillily
2楼-- · 2019-02-28 18:01
LabelContactNumber.Text = (Session["sContactNumber"] != null)
                              ? Session["sContactNumber"].ToString()
                              : string.Empty //or whatever default value your want;
查看更多
Lonely孤独者°
3楼-- · 2019-02-28 18:04
int contactNumber = -1;
if( int.TryParse( Session[ "sContactNumber" ], out contactNumber ) == false )
{
    LastContactNumber = "N/A";
}
else
{
    LastContactNumber = contactNumber.ToString( );
}
查看更多
地球回转人心会变
4楼-- · 2019-02-28 18:07

Problem : it is failing because you are assigning the Integer type into String. here you need to use explicit conversion to convert the Integer type into String type.

Solution : if you want to check wether contact number can be parsed to int or not before assigning it into TextBox use TryParse method

int contact;
if(int.TryParse(Session["sContactNumber"],out contact))
   LabelContactNumber.Text = contact.ToString();
else
   LabelContactNumber.Text = "Invalid Contact!";
查看更多
登录 后发表回答