如何将DataReader值转换为整数变量

问题描述:


我有来自数据库的datareader值是dr = 10,30,0,12,0,42,....
我无法计算总数,即代码如下:

Hi,
i have the datareader values are dr= 10,30,0,12,0,42,... from database.
i am not able to calculate the total count i.e the code as follows:

while (dr.Read())
                {
                    int Count = 0;
                    Count = Count + int.Parse(dr["TotalCount"].ToString());
                }



执行此操作时,出现类似以下错误:
索引OutOfRange异常.

请给我一个有效的解决方案.

谢谢与问候,
Raghu.



while executing this i am getting an error like:
Index OutOfRange exception.

please give me a valid solution.

Thanks&Regards,
Raghu.

好吧,每次重置Count时,您都不会得到像这样的总和,假设您正确地清空了DataTable,则可以执行以下操作:
Well you wont get any sum like that as you are resetting the Count each time, assumiung that you have raead out the DataTable correctly you could do this:
                    int Count = 0;
while (dr.Read())
                {

                    Count = Count + int.Parse(dr["TotalCount"].ToString());
                }



您还应该检查是否可以使用TryParse insted将字符串解析为整数..



You should also check that you could Parse the string as an integer, using TryParse insted..