Null value in sum

Asked

Viewed 211 times

2

I’ve got a problem with mine query, when there are values in the table the sum normally happens as programmed:

string nomeProd = item.SubItems[0].Text;
                double Quantidade = Convert.ToDouble(item.SubItems[2].Text);
                cmdQry.CommandText = "SELECT SUM(quantidadeMat) FROM tbl_EstoqueMat WHERE reservadoMat=False AND nomeMat=@nome";

                cmdQry.Parameters.Clear();
                cmdQry.Parameters.Add(new OleDbParameter("@nome", nomeProd));

                try
                {
                    //SOMA AQUI, OCORRE NORMALMENTE QUANDO HÁ DADOS NA TABELA
                    double soma = Convert.ToDouble(cmdQry.ExecuteScalar());

When no data is in the table, or not available for summation, the following error occurs:

Erro de DBNull

The value is returned null. How to deal with this type of problem?

I use Oledb, that is, Access and C#.

2 answers

3


First of all you have two problems in your code. The first is the use of double, this is not appropriate. The second is that you are converting something that you cannot guarantee can be converted, it should be something like this:

if (!decimal.TryParse(item.SubItems[2].Text, out var quantidade)) //faz alguma coisa se deu erro e encerra a execução

But the specific problem is precisely what is indicated in your question, there is situation that the returned value is null, so you have to work with this option and treat this appropriate value. What you shouldn’t do is let her make an exception and catch her to do something. Almost every exception capture in code is wrong and is gambiarra of those who do not want to fix the error in their code.

Just as I fixed the above checked problem if it went all right in this case I would also have to do something similar:

var resultado = cmdQry.ExecuteScalar();
if (resultado == DBNull.Value) //faz alguma coisa aqui para tratar o erro e encerra
var soma = ToDecimal(resultado);

I put in the Github for future reference.

In case I put one using static System.Convert; at the beginning of the code.

This way the conversion will only be made if it is not null.

Use a rule: if you don’t know how to use a language mechanism like the exception or type double, among others, do not use. When you use something you do not understand how it works you end up entering this situation:

Fiat 147 todo detonado andando pelas ruas

  • Okay, good answer, that’s what I was looking for. Thanks for the tips. And one more thing: why is double usage inappropriate? The values in my bank are double. Does this cause any problem? And why opt for decimal? I see many using. Grateful

  • 1

    Yes, cause, read the link that I posted. I don’t even know if I should accept null in the snare. And this https://answall.com/a/56299/101 or this https://answall.com/q/15261/101.

  • There is no null in the column, my query filters only specified data, and it may occur that none is available, or some are available. Thank you so much for the answers and tips, helped me a lot!

  • Set "not available"

  • Basically, it’s a stock system, and in the case of the code, I’m dealing with the stock of raw materials. When a production order is opened, the system calculates the required amount of raw material and offers the user option to select which one to use. When one is selected it is reserved and cannot be used in another production due to the handling processes at the factory. This code you helped me with is to check the quantity of the materials in stock. If there is no availability there will be no production yet.

  • You have described your software, but not what is "not available". Because if this is 0, then the sum should occur normally and your problem is another.

  • Not being available means that the matter is marked as "Reserved", that is, the code will ignore the matter, which will have quantity, either "500" or "5", but the code should not add.

  • I get it, then nothing comes into the sum, then it’s null anyway.

  • One more thing, now the variable "result" is coming back empty and not null. How should I deal?

  • What does "empty mean"?

  • It says that the value is "{ }". By performing if the way you put it, it simply jumps to "Else"

  • I didn’t put else some. You need to see this right, because either you did something you shouldn’t have done or something different is happening than it should be. Then I will say that the question does not have all the data it should. This data should not happen in correct code.

  • Yeah, you didn’t put the else, but the problem is he doesn’t read the resultado null. It does not execute the if that you put.

  • There is something missing from your question. It only shows a null error.

  • Yes, but there’s another problem now. Yours if does not work. The resultado is not returned null, and the part where you place var soma = ToDecimal(resultado); does not work, it presents the same exception, "Object cannot be converted from Dbnull into other types".

  • 1

    Try switching null for DBNull.Value.

  • Thank you so much! It’s 100% now.

Show 12 more comments

0

You can use "catch" to handle the error received.

Ex:

            string nomeProd = item.SubItems[0].Text;
            double Quantidade = Convert.ToDouble(item.SubItems[2].Text);
            cmdQry.CommandText = "SELECT SUM(quantidadeMat) FROM tbl_EstoqueMat WHERE reservadoMat=False AND nomeMat=@nome";

            cmdQry.Parameters.Clear();
            cmdQry.Parameters.Add(new OleDbParameter("@nome", nomeProd));

            try
            {
                //SOMA AQUI, OCORRE NORMALMENTE QUANDO HÁ DADOS NA TABELA
                double soma = Convert.ToDouble(cmdQry.ExecuteScalar()); 

            }
            catch 
            {
              MessageBox.Show("O valor recebido é nulo");
            }
  • This is not correct, although potentially working.

  • Congratulations on the answer, I will use for learning @Maniero

Browser other questions tagged

You are not signed in. Login or sign up in order to post.