I want to get the total of the books in the database using sum but if there is no book in the database, it gives error. I want it to write 0 instead of error. My codes are below.
OleDbCommand cmd = new OleDbCommand("select sum(adet) from kitaplar25", conn);
cmd.Parameters.AddWithValue("@adet", label14.Text);
label14.Text = cmd.ExecuteScalar().ToString();
Rajkiran SwainPosted Apr 7, 2023, 3:48 PM
Rajkiran SwainPosted Apr 8, 2023, 4:01 PM
If it will be helpful, please accept the answer.
Mehmet FatihPosted Apr 8, 2023, 8:23 AM
Thanks you everyone for your efforts. I have solved the problem changing something in Rajkiran Swain's answer like that if (result != DBNull.Value).
Mehmet FatihPosted Apr 8, 2023, 7:32 AM
You all are trying to find solution to my problem but I am very sorry to infirm that all of them give error. I am usinf access database. Maybe it depends on it. The closest answer is Rajkiran Swain's answer. The only problem with Rajkiran Swain's solution is that it doesn't write zeros.
Muhammad Imran AnsariPosted Apr 8, 2023, 4:31 AM
With an alternative way, you can use the ternary operator to provide a default value for null values. Here's an example:
Amit MohantyPosted Apr 8, 2023, 3:56 AM
Mehmet FatihPosted Apr 7, 2023, 8:34 PM
I am sorry but none of them gives 0 result.
Rajkiran SwainPosted Apr 7, 2023, 6:26 PM
Try this one too.
Tuhin PaulPosted Apr 7, 2023, 5:25 PM
we use the
COALESCEfunction to return the sum of books (SUM(adet)) or 0 if the result isNULL. We also use theASkeyword to alias the result astotal. Finally, we assign the result to thelabel14.Textproperty.Tuhin PaulPosted Apr 7, 2023, 5:24 PM
To handle the case where there are no books in the database and avoid the error, you can use the
COALESCEfunction in your SQL query to replace theNULLvalue with 0.Jignesh KumarPosted Apr 7, 2023, 4:04 PM
Hi,
Please check below and small change is query for isNull() function will solve your issue