Read values from a column - C #

1

I need to read the values of a column called Code_Article and put them, but when the column is still empty, I run and give the error: p>

  

The object reference was not defined as an instance of a   object.

Here is my code:

conn.Open();
SqlCommand cmd6 = new SqlCommand("SELECT Code_Article FROM ArticleBarCode", conn);
Int32 codeexistente = (Int32)cmd6.ExecuteScalar();
conn.Close();

What can I change in the code for when the column is empty, do not give error, but return for example 0?

    
asked by anonymous 28.04.2017 / 17:45

2 answers

1

This error happens because the return is nullo and you try to write to an integer, so it returns that error.

To solve, you can use the ISNULL sql server, like this:

SELECT ISNULL(Code_Article,0) FROM ArticleBarCode

So, if Code_Article is empty or nullo will return 0 for your application.

    
28.04.2017 / 18:30
1

First: check that cmd6 is not null, this is a possibility.

For your conversion, it is not a good idea to do this direct , since the return of ExecuteScalar() can be null and this can also cause an error.

A good idea is to use Convert.ToInt32 , if you are sure that the values can only be null or an integer:

Int32 codeexistente = Convert.ToInt32(cmd6.ExecuteScalar());

If this can not be guaranteed, the best thing to do is to receive this result in int? and validate it

int? code = cmd6.ExecuteScalar() as int?;
Int32 codeexistente = code == null ? 0 : code;

What I would simplify for

Int32 codeexistente = (cmd6.ExecuteScalar() as int?) ?? 0;

And you can also do direct to query , using IsNull of SQL Server

SqlCommand cmd6 = new SqlCommand("SELECT IsNull(Code_Article, 0) FROM ArticleBarCode", conn);
    
28.04.2017 / 17:48