Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.IndexOutOfRangeException: Index was outside the bounds of the array [duplicate]

I am developing an ATM Software as a home work in which i want to know the total amount of transaction which is processed today, for this purpose I am writting the following code

 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;
            }
        }

But i am getting the exception System.IndexOutOfRangeException: Index was outside the bounds of the array, although in database more than one records are available which are getting by running the same query in query window. But I don't know how to get it through coding.

Please help me.

Regards

like image 473
Snake Avatar asked Jan 01 '12 12:01

Snake


1 Answers

Change the while like this.

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

There is no need of an i there

like image 90
naveen Avatar answered Oct 07 '22 13:10

naveen