IndexOutOfRangeException

IndexOutOfRangeException

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

(4个答案)


4年前关闭。




我正在开发一个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:索引超出了数组的范围,尽管在数据库中有多个记录可用,这些记录是通过在查询窗口中运行相同的查询来获取的。但是我不知道如何通过编码来获得它。

请帮我。

问候

最佳答案

那是因为您尝试读取太多的IMO列。

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

                i++;

            }

谁说列多于行?
似乎您正在尝试对单个列求和。

通过选择所有行来浪费时间。如果您正在寻找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;

09-10 10:37