c# - 系统.IndexOutOfRangeException : Index was outside the bounds of the array

标签 c# database sql-server-2008 sql-server-2005

<分区>

我正在开发一个 ATM 软件作为家庭作业,我想知道今天处理的交易总额,为此我正在编写以下代码

 public decimal getDayTransaction(int accountid, string date, string transactiontype)
        {
            decimal totalamount = 0;
            int i = 0; 
            string connectionString = 
                     "Persist Security Info=False;User ID=sa; Password=123;Initial Catalog=ATMSoftware;Server=Bilal-PC";
            try
            {
                using (SqlConnection connection = 
                                 new SqlConnection(connectionString))
                {


                    SqlCommand command = new SqlCommand(
                         "Select Amount From [Transaction] where AccountID = "
                         + accountid + " AND CurrDate ='" + date
                         + "' AND TransactionType = '" 
                         + transactiontype + "';", connection);

                    connection.Open();
                    SqlDataReader dr = command.ExecuteReader();
                    while (dr.Read())
                    {
                        totalamount += Convert.ToDecimal(dr.GetString(i));

                        i++;

                    }
                    return totalamount;
                }


            }
            catch (Exception e)
            {

                return -1;
            }
        }

但我收到异常 System.IndexOutOfRangeException:索引超出数组范围,尽管在数据库中有多个记录可用,这些记录是通过在查询窗口中运行相同的查询获得的。但是我不知道如何通过编码得到它。

请帮帮我。

问候

最佳答案

像这样改变 while。

while (dr.Read())
{
    totalamount += Convert.ToDecimal(dr.GetString(0));
}

那里不需要i

关于c# - 系统.IndexOutOfRangeException : Index was outside the bounds of the array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693044/

相关文章:

c# - 最好将错误代码/消息保存在数据库或字典中?

c# - 如何在不使用 math.pow 的情况下分解 x^(x+1)

C#:整数集的类型安全(例如枚举)

c# - 向 SQL Server 数据库中插入语句

sql - 全文搜索 CONTAINSTABLE

c# - 解决 C# 中的线程冲突

mysql - 来自 TSV 文件的 Seed Rails 数据库 (MySQL)

sql - 保持 AUTO_INCREMENT 字段是不合适的设计?

sql - 我如何正确地装框这个校对?

c# - 如何使用 C# 检索存储过程?