繁体   English   中英

错误:无法将类型为“ System.Int32”的对象转换为类型为“ System.String”的对象

[英]Error: Unable to cast object of type 'System.Int32' to type 'System.String'

我已经完成了完美的编码注册页面,登录,现在UpdateCustomer页面有错误-背景信息:我正在使用Microsoft Access作为数据源

    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"];

除了LabelContactNumber.Text = (string)Session["sContactNumber"]以外,这里一切都很好。

我相信这是因为在Access中只有ContactNumber设置为Int,其余的是Text,所以当我使用(字符串)时没有错误。

问题:失败,因为您正在将Integer类型分配给String。 在这里,您需要使用显式转换将Integer类型转换为String类型。

解决方案:如果要检查是否可以将联系电话号码解析为int,然后再将其分配给TextBox,请使用TryParse方法

int contact;
if(int.TryParse(Session["sContactNumber"],out contact))
   LabelContactNumber.Text = contact.ToString();
else
   LabelContactNumber.Text = "Invalid Contact!";
LabelContactNumber.Text = (Session["sContactNumber"] != null)
                              ? Session["sContactNumber"].ToString()
                              : string.Empty //or whatever default value your want;
int contactNumber = -1;
if( int.TryParse( Session[ "sContactNumber" ], out contactNumber ) == false )
{
    LastContactNumber = "N/A";
}
else
{
    LastContactNumber = contactNumber.ToString( );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM