Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm creating a Windows Forms App (.NET Framework) and trying to connect to a MySQL Database on my LAN.

The code I'm using is:

C#
private void button1_Click(object sender, EventArgs e)
{
    connString = $"SERVER={server}; DATABASE={database};
                 UID={username}; PASSWORD={password}";
    try{
            conn = new MySqlConnection();
            conn.ConnectionString = connString;
            conn.Open();
            MessageBox.Show("Connected.");
       }
       catch (MySqlException ex)
       {
            MessageBox.Show(ex.Message);
       }
}


When I step through the code and it gets to conn.Open();
I receive the following error:
System.InvalidCastException HResult=0x80004002 Message=Object cannot be cast from DBNull to other types.

However, the database opens and I can Add, Delete and Query the database.

Anyone tell this novice what is going on?

What I have tried:

I've Googled the error and none of it seems to make sense (to me) as
the database connection is fine.
Posted
Updated 3-Nov-23 4:11am
v3
Comments
dbrenth 2-Nov-23 13:41pm    
I don't see where you have initialized the variables "server", "database", "username" and "password". When you set a string with the $ prefix, the parts in {} will be replaced with the variables or functions inside the brackets. If there is nothing, NULL will be returned and that could be your NULL that is causing the Invalid Cast Exception.

1 solution

check out the official answer at : https://stackoverflow.com/questions/74060289/mysqlconnection-open-system-invalidcastexception-object-cannot-be-cast-from-d[^]

The gist of that is: "Change MySql.Data.MySqlClient to MySqlConnector and the problem was solved"
 
Share this answer
 
Comments
RogerJones 2-Nov-23 13:47pm    
Thank you. I was just coming to say I'd sorted it out when i saw your answer.
I changed from MySql.Data 8.2.0 to MySqlConnector and it works fine.

Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900