I believe the error is generated on this line:
DateTime meuValor = Convert.ToDateTime(command.ExecuteScalar());
According to the question command.ExecuteScalar()
can return either a date, in which case all right, or a DBNull
, which is when the error occurs because DBNull
cannot be converted to date and the method generates the InvalidCastException
mentioned in the question.
Another problem with this line is that meuValor
is the type DateTime
who is descended from ValueType
which by definition cannot receive null
.
Another critical point is the line:
if (meuValor.equals(null)) ...
It still does not generate an error but from the moment the previous error is fixed, this line will generate a NullReferenceException
.
The solution is simple just work the value obtained with command.ExecuteScalar()
, suit the type of meuValor
for Nullable
, which can receive null, and fix the line which will then generate error by matching the check.
command.Connection = connection;
command.CommandText = "select DateDesabled from IdUser where UserName = @userName";
command.Parameters.AddWithValue("userName", user.UserName);
// Obtem o valor bruto do DB
var rawMeuValor = command.ExecuteScalar();
// Trabalha rawMeuValor comparando com DBNull. Se afirmativo meuValor referenciará null senão referenciará uma data
DateTime? meuValor = DBNull.Value.Equals(rawMeuValor)? null : Convert.ToDateTime(rawMeuValor);
Debug.WriteLine("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
Debug.WriteLine("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+meuValor);
DateTime CurrentlyDay = DateTime.Today;
//Não sei a versão do seu compilador então não usei meuValor is null
if (meuValor == null) /* Faça alguma coisa */
Because it is not nullable...?
DateTime? meuValor
– Leandro Angelo
Leandro Angelo Explaining better, in my table there is a field Datalock, where at first this date is not filled. This date is assigned by a support person.. So you wanted to check: select Datalock from User Where Username = @username; with this select would like to check this date if it is NULL the user has no lock otherwise the user is locked. ?
– Gabriel Silva
If you receive from the bank a Date that can be null... you must use the type
DateTime?
– Leandro Angelo
@Leandroangelo the return of
ExecuteScalar()
is notnull
. ISDBNull
.– Augusto Vasques
Very well noted @Augustovasques
– Leandro Angelo