Invalid Cast Exception was unHandled MySQL

前端 未结 2 709
自闭症患者
自闭症患者 2021-01-23 05:24

When I run the program I get this error:

Invalid Cast Exception was unHandled

This is part of form for fill a database, and visual

2条回答
  •  太阳男子
    2021-01-23 06:08

    I strongly suspect, you parameterize your LIKE part in a wrong way. You need to use %..% at least to figure out you try to get values that includes those string. Like;

    sqlCommand.Parameters.AddWithValue("@pNombre", "%" + txtNombre.Text + "%");
    sqlCommand.Parameters.AddWithValue("@pApellido", "%" + txtApellido.Text + "%");
    

    Don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.

    Also use using statement to dispose your connection and command automatically instead of calling (in somewhere maybe in your code) Close or Dispose methods manually.

    By the way, be aware, COUNT(*) returns BIGINT in MySQL and this type mapped with Int64 in .NET side. As Steve mentioned, you can parse this value instead of casting like;

    int UsuarioExiste = int.Parse(sqlCommand.ExecuteScalar());
    

    or you can define your UsuarioExiste as long which seems more consistent(?) I think.

    long UsuarioExiste = (long)sqlCommand.ExecuteScalar();
    

提交回复
热议问题