0

I have seen similar threads like this where the solution is a tertiary if.

My question is, why even get such an error if Strings are nullable?

I am reading a value of a text column in access using ado.net. Whenever there is a row with an empty text column i get that error.

Culprit:

while (dr.Read())
{
      UserList.Add(new UserInfo()
      {
        .
          DestributionGroup = (string)dr["Destribution Group"]
        .
      }
}
class UserInfo
{
.
    public string DestributionGroup;
.
}

Edit:

So in other words I have to convert all of my strings that I am reading from the DB into a line similar to this?

return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString ()

No other way around it?

Community
  • 1
  • 1
AngelicCore
  • 1,413
  • 3
  • 22
  • 40

2 Answers2

3

Because null != DBNull.Value.

But you can check if it the value in the DataReader is null with the IsDbNull method:

DestributionGroup = dr.IsDbNull("Destribution Group") ? "" : dr.GetString("Destribution Group");
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You can use this if you don't mind DestributionGroup being set to null when dr["Destribution Group"] is DBNull.Value :

DestributionGroup = dr["Destribution Group"] as string;
Moe Sisko
  • 11,665
  • 8
  • 50
  • 80