Object cannot be cast from DBNull to other types.

BgnerNprg207 286 Reputation points
2024-05-28T11:44:27.7833333+00:00

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

private void Button2_Click(object sender, EventArgs e)
        {
            
            
            string mysqlcon = "SERVER=192.XXX.XXX.XXX;PORT=XXXX;DATABASE=XXXX;UID=XXXX;PASSWORD=XXXX;";
            MySqlConnection mysqlconnection = new MySqlConnection(mysqlcon);
            try
            {
                mysqlconnection.Open();
                label2.ForeColor = System.Drawing.Color.Green;
                label2.Text = "Connected";
            }
            catch (Exception ex)
            {
                label2.ForeColor = System.Drawing.Color.Red;
                label2.Text = ex.Message;
            }
            finally
            {
                mysqlconnection.Close();
            }
        }

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.

C#
C#
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
    2024-06-14T05:59:09.08+00:00

    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