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
Change the while like this.
while (dr.Read())
{
    totalamount += Convert.ToDecimal(dr.GetString(0));
}
There is no need of an i there
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With