不能在asp.net c#中隐式地将类型'int'转换为'string'

不能在asp.net c#中隐式地将类型'int'转换为'string'

问题描述:

请帮助纠正此错误以将int转换为字符串我的代码在c#中是





Pls some one help to correct this error to convert int to string My code is in c# is


Session["priceday1"] = Label2.Text ;

               Label4.Text = Convert.ToInt32(Session["priceday1"].ToString())  / 44;







在第二行有错误将int转换为字符串so.Pls一些帮助,如何纠正这个错误。




In second line there is error to convert int to string so.Pls some one help that how to correct this erro.

我不会使用转换at所有。当字符串无法转换时,您必须捕获一个丑陋的异常。 int.TryParse()是一个更好的选择:



I would not use Convert at all. You would have to catch an ugly exception when the string cannot be converted. int.TryParse() is a much better choice:

int Result;


if (int.TryParse(Session["priceday1"], out Result))
{
    // parsing was successful
    Result /= 44;
    Label4.Text = Result.ToString();
}
else
{
    // conversion not successful, handle error here
}





除此之外,这有什么意义呢?为什么要将字符串转换为int,只是为了获取int并将其再次转换为字符串?为什么不直接将会话中的原始字符串直接分配给标签的文本属性?啊,我明白了!我忽视了这个部门。



Besides that, what sense does all this make? Why do you convert a string to int, just to take the int and convert it to a string again? Why don''t you just assign the original string from the session directly to the label''s text property? Ahh, I got it!. I overlooked the division.


就这样做



just do this

Label4.Text = (Convert.ToInt32(Session["priceday1"])  / 44).ToString();


try this
 
Session["priceday1"] = "5464";
              // Session["priceday1"] = 5464;
           int finalPrice;
           if (Int32.TryParse(Session["priceday1"].ToString(), out finalPrice))
           {
               finalPrice = finalPrice / 44;
               Label1.Text = finalPrice.ToString();
           }
           else
           {
               Label1.Text = "Invalid";
           }