Object cannot be cast from DBNull to other types.

BgnerNprg207 286 Reputation points

Good day, I want to check my DB connection and here's my code.

private void Button2_Click(object sender, EventArgs e)
            MySqlConnection mysqlconnection = new MySqlConnection(mysqlcon);
                label2.ForeColor = System.Drawing.Color.Green;
                label2.Text = "Connected";
            catch (Exception ex)
                label2.ForeColor = System.Drawing.Color.Red;
                label2.Text = ex.Message;

now, when I click one's the CHECK button it shows like this.

User's image

It show's the error message that say. "Object cannot be cast from DBNull to other types."

Now, when I click the check button twice, it shows like this.

User's image

It's shown Connected. I don't know why.

Please help me to fix this problem. Thank you so much.

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,535 questions
{count} votes

1 answer

Sort by: Most helpful
  1. 感恩的❤ 155 Reputation points

    This error shouldn't have happened when you have a connection with your SQL server.

    It's something to do with the "Data Insert", which means you've inserted an Null value into a non-value field.

    So plz make sure you haven't pressed the "Insert" button with an empty textbox.

    The solution is:

    1, Click the "CHECK" first.

    2, Write something into the TextBox.

    3, Click "Insert".

    0 comments No comments