0
I have a query in ADO . NET with the aim of return the amount of records I have in the bank based on last month and year. For example, I pass the date "27/01/2021" and receive the amount of records I have in the bank for "01/2021". The problem happens if I have no record recorded in the bank, then I get the error:
Tofrangeexception argued: Index was out of range. Must be non-negative and Less than the size of the Collection. (Parameter 'index') System.Collections.Generic.list.get_Item(int index)
If I already have at least one record in the bank I don’t get this error, I tried a few things, but I couldn’t get any solution for this error. Follow my query:
public int RetornaQuantidadeCuponsMes(string numDocumento, string idProduto, string dataImportacao)
        {
            var conexao = AbrirConexao();
            var comando = conexao.CreateCommand();
            comando.CommandText =
                "SELECT DATE_FORMAT(@dataEfetivacao,'%Y-%m') AS data, " +
                "(SELECT COUNT(cupom) FROM campanhaCupons AS c2 " +
                "WHERE DATE_FORMAT(c2.dataEfetivacao,'%Y-%m') = data AND numDocumento = @numDocumento  AND idProduto = @idProduto) " +
                "AS qtdCupons " +
                "FROM campanhaCupons AS c1";
            comando.Parameters.AddWithValue("numDocumento", numDocumento);
            comando.Parameters.AddWithValue("idProduto", idProduto);
            comando.Parameters.AddWithValue("dataEfetivacao",
                Convert.ToDateTime(dataImportacao).ToString("yyyy/MM/dd"));
            var cooperado = ExecutaComandoComRetorno(comando);
            var cuponsNoMes = cooperado[0]["qtdCupons"];
            return Convert.ToInt32(cuponsNoMes);
        }
Error on the line of
var cuponsNoMes?– Natan Fernandes
"The problem happens if I have no record recorded in the bank" based on that statement, if you do so
var cuponsNoMes = cooperado[0]["qtdCupons"];without validating first ifcooperadoreturned some value will give error, first need to validate if you have data incooperado– Ricardo Pontual