加到整数字符串C# [英] add to integers String C#

查看:93
本文介绍了加到整数字符串C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lblUnit.Text = (Int32.Parse(Session["Price"].ToString()) + Int32.Parse(Session["EfPrice"].ToString())).ToString();




这给出了错误:输入字符串的格式不正确"




This gives the error: "Input string was not in correct format"

Thanks for your time!

推荐答案

检查您在会话中输入了哪些值-其中一个("Price"或"EfPrice")不是数字值,或者包含无效字符.
Check what values you have put into the Session - one of them (either "Price" or "EfPrice") is not numeric, or contains invalid characters.


lblUnit.Text = (Int32.Parse(Session["Price"].ToString()) + Int32.Parse(Session["EfPrice"].ToString())).ToString();
// ------------------------------------------^                                            ^
// ---------------------------------------------------------------------------------------|



首先存储在Session变量中的是什么?如果Session变量的内容已经是一个字符串,则调用ToString()是多余的.如果已经是一个int转换将使用更少.如果是这样,则EfPrice或/和Price已经包含int,您可以将它们加起来.我认为尽管从错误消息中可以看到,其中一个变量包含一个浮点数或一个双精度值(也许也包含两者).将double转换为字符串可以很容易地对该字符串进行int转换.

如果您要在此处处理浮点数/双精度数,请使用正确的方法进行如下所示的转换:



What is it that was stored in the Session variable in the first place? If the content of the Session variable is already a string calling ToString() is superflous. If it was already an int the conversion would be use less. If it were so that EfPrice or/and Price already contained ints you could just sum them up. I think though from the error message you are receiving that one of the variables contains a float or a double value (maybe also both). A double converted to a string can make an int conversion on that string fail quite easily.

If you''re dealing with floats/doubles here use the correct methods to do the conversions like here:http://social.msdn.microsoft.com/Forums/is/csharpgeneral/thread/3161a030-4136-4f43-a811-083ef87cd189[^].

Regards,

—MRB


,如果一个会话变量或两个变量都包含字母或特殊字符.
在这种情况下,只有您会得到例外
if once of your session variable or both of the variables contains alphabets or special characters .
in this case only you will get the exception


这篇关于加到整数字符串C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆