2

I am working on application in that fetching record from database.but when fetching char datatype of value is null then it shows error. here is my Code:

SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            lstServiceCall_Activity.Add(new OpportunityActivity()
            {
                Recontact = Convert.IsDBNull(reader["Recontact"]) ? (DateTime?)null : Convert.ToDateTime(reader["Recontact"]),
                endDate = Convert.IsDBNull(reader["endDate"]) ? (DateTime?)null : Convert.ToDateTime(reader["endDate"]),
                Details = (reader["Details"]) == DBNull.Value ? null : Convert.ToString(reader["Details"]),
                Location = (reader["Location"]) == DBNull.Value ? 0 : Convert.ToInt32(reader["Location"]),
                CardCode = (reader["CardCode"]) == DBNull.Value ? null : Convert.ToString(reader["CardCode"]),
                Action = Convert.ToChar(reader["Action"]),
                Priority = Convert.ToChar(reader["Priority"]),
                CntctType = Convert.ToChar(reader["CntctType"]),
                assignedTo = Convert.ToString(reader["AttendUser"])
            }
            );
        }       

for char how to set dbnull value. Please give some suggestion.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Anuja
  • 97
  • 1
  • 1
  • 11
  • char is a value type. Cannot be set to null, [and then follow this answer](http://stackoverflow.com/questions/5812904/can-i-set-a-char-or-datetime-to-null) – Steve Oct 14 '16 at 07:20

2 Answers2

3

You can't set a char to null, so you either have to make it nullable by adding a ? after char, or use the null-terminator as an identifier for an 'empty' character:

char? canBeNull = null;

char nullTerminated = '\0';

Which option you choose is up to you, but I would option 1, since that makes clear what your intentions were with this variable.

So the end result would be something like this:

char? Priority = reader["Priority"] != DBNull.Value
                 ? Convert.ToChar(reader["Priority"])
                 : (char?)null;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1
Action  = (reader["Action"]) == DBNull.Value ?'\0' : Convert.ToChar(reader["Action"]),

Use like this.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197