This is because you are trying to read too many IMO columns.
while (dr.Read()) { totalamount += Convert.ToDecimal(dr.GetString(i)); i++; }
Who says more columns than rows? It seems you are trying to summarize a single column.
You lose time by selecting all the rows. if you are looking for SUM, use SUM(COLUMN1) instead
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;
source share