0
votes

I have an error on return Convert.ToInt32(dataGridView1[0, Row].Value); it says that 'Object cannot be cast from DBNull to other types.' My database field on student ID is int. Here is my code:

 public int GetStudentID()
    {
        // The Student ID is the first cell of the current row
        int Row = dataGridView1.CurrentRow.Index;
        return Convert.ToInt32(dataGridView1[0, Row].Value);
    }

    public string GetISBN()
    {
        // The ISBN is the second cell of the current row
        int Row = dataGridView1.CurrentRow.Index;
        return dataGridView1[1, Row].Value.ToString();
    }
4
What would you like your code to do if it finds a null in the database? - dcaswell

4 Answers

1
votes

There a two possible problems here:

  1. You are getting nulls from the database but always expecting a value
  2. You are getting nulls from the database but not handling them

For problem 1, ensure the query that you're executing cannot allow null values. Maybe you're missing a filter...?

For problem 2, you need to check for null values:

public int GetStudentID()
{
    int Row = dataGridView1.CurrentRow.Index;
    var val = dataGridView1[0, Row].Value;

    if (object.Equals(val, DBNull.Value))
    {
        /* either throw a more appropriate exception or return a default value */
        // let's assume a default value is fine
        return -1;
    }

    return Convert.ToInt32(val);
}
0
votes

Your dataGridView1[0, Row].Value must be NULL

Check for NULL or use a try-catch block with NullReferenceException like below

try
{
 return Convert.ToInt32(dataGridView1[0, Row].Value);
}
catch(NullReferenceException e)
{
return 0;//No such student ID when NULL is encountered.
}
0
votes

You should check for DBNull.Value. It is not the same as null.

if(DBNull.Value != dataGridView1[0, Row].Value)
{
    // do convertion, etc
}
else
{
    // handle null case
}
0
votes

It's handy to have a method to manage this little detail, e.g.:

email = Database.GetValueOrNull<string>(sqlCommand.Parameters["@Email"].Value);

Implemented like this:

public static T GetValueOrNull<T>(Object column)
{
    // Convert   DBNull   values to   null   values for nullable value types, e.g.   int? , and strings.
    //   NB: The default value for non-nullable value types is usually some form of zero.
    //       The default value for   string   is    null .

    // Sadly, there does not appear to be a suitable constraint ("where" clause) that will allow compile-time validation of the specified type <T>.

    Debug.Assert(Nullable.GetUnderlyingType(typeof(T)) != null || typeof(T) == typeof(string), "Nullable or string types should be used.");

    if (!column.Equals(DBNull.Value)) // Don't trust   ==   when the compiler cannot tell if type <T> is a class.
        return (T)column;

    return default(T); // The default value for a type may be   null .  It depends on the type.
}

Moving data from a variable to a database parameter with null conversion may be accomplished thusly:

sqlCommand.Parameters.AddWithValue("@Serial", serial ?? (object)DBNull.Value);