0

I'm using the mySql connector with phpMyadmin and i try to verify if a value is a DBNull cause it make my project bug and I didn't succeed to find a way to verify it.

I tried:if( aReader.GetString("ColumnName") != DBNull.value){...} but it doesn't work.

I have this error:

System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.String'.'

the code i made is :

MySqlDataReader aReader = aMySqlCommand.Command.ExecuteReader();
while(aReader.Read())
{
    aReader.GetString("columnName"); // there's the place where I get my error
}

thanks for you answer

stuartd
  • 70,509
  • 14
  • 132
  • 163
BenBel
  • 49
  • 1
  • 4

2 Answers2

1

MySqlDataReader has a method to check for null: reader.IsDBNull(index). https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.isdbnull?view=dotnet-plat-ext-3.1

Jacob Huckins
  • 368
  • 2
  • 15
0

Check if value is null. do different things depending on if it's actually null or not.

if(Convert.IsDBNull(aReader["columnName"])) {
  //do things if null
} else {
  aReader.GetString("columnName");
}
Mikael
  • 1,002
  • 1
  • 11
  • 22