System.IndexOutOfRangeException:索引超出数组的范围

Sna*_*ake 5 c# database sql-server-2005 sql-server-2008

我正在开发一个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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

请帮我。

问候

Sha*_*hai 3

在我看来,那是因为您试图阅读太多专栏。

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

                i++;

            }
Run Code Online (Sandbox Code Playgroud)

谁说列多于行?看起来您正在尝试对单列求和。

选择所有行是在浪费时间。如果您正在寻找 SUM,请SUM(COLUMN1)改用

                SqlCommand command = new SqlCommand("Select SUM(Amount) as sAmount 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(0));
                    break; // Only read once, since it returns only 1 line.

                }
                return totalamount;
Run Code Online (Sandbox Code Playgroud)