简体   繁体   English

system.invalidcastexception 'object cannot be cast from dbnull to other types.'

[英]system.invalidcastexception 'object cannot be cast from dbnull to other types.'

I am doing a login in C#.我正在用 C# 登录。 When I press the button to login which has the method that validate the user it throws this exception "InvalidCastException: object cannot be cast from dbnull to other types.".当我按下具有验证用户方法的登录按钮时,它会抛出此异常“InvalidCastException:对象无法从 dbnull 转换为其他类型。”。

I already verified almost anything.我已经验证了几乎所有内容。 My database is correct.我的数据库是正确的。 Both of columns of the tables are VARCHAR.表的两列都是 VARCHAR。 In C# I am trying to save them into string so it shouldn't throw that exception.在 C# 中,我试图将它们保存到字符串中,因此它不应该抛出该异常。 The exception is also thrown if I put the wrong name and password.如果我输入错误的名称和密码,也会抛出异常。

The problem should be inside of "while (reader.Read())" but I'm not sure...问题应该在“while (reader.Read())”中,但我不确定...

This method is called by the button_OnClick method.此方法由button_OnClick方法调用。

public User validateUser(string name, string pass)
{
    User user = null;

    String query = "SELECT * FROM users WHERE name = @name AND password = @password;";
    try
    {
        con = dbConnect.getConnection();

        if (con != null)
        {
            con.Open();
            using (MySqlCommand cmd = new MySqlCommand(query, con))
            {
                cmd.Parameters.Add(new MySqlParameter("@name", name));
                cmd.Parameters.Add(new MySqlParameter("@password", pass));

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {

                            string nam = Convert.IsDBNull(reader["name"]) ? "" : reader["name"].ToString();
                            string password = Convert.IsDBNull(reader["password"]) ? "" : reader["password"].ToString();

                            user = new User(nam, password);

                            //   user = new User(reader["name"].ToString(), reader["password"].ToString());
                        }
                    }
                }
            }
        }
    }
    catch (MySqlException error1)
    {
        MessageBox.Show(" 123 " + error1.Message);
    }
    catch (InvalidCastException error2)
    { 
        MessageBox.Show(" 789 " + error2.Message);
    }
    return user;
}

And this is the button_OnClick method:这是button_OnClick方法:

private void button1_Click(object sender, EventArgs e)
{
    string name = txtUser.Text;
    string pass = txtPass.Text;

    if (name == "" || pass == "")
    {
        MessageBox.Show("Rellena los campos.");
    }
    else
    {
        try
        {
            user = userDao.validateUser(name, pass);
        }
        catch (InvalidCastException ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
        if (user == null)
        {
            txtMsg.Text = "ERROR";
        }
        else
        {
            txtMsg.Text = "CORRECTO";
        }
    }
}

The problem is that Convert.IsDBNull(reader["name"]) first calls reader["name"] to extract the value from the DbDataReader , before it checks for DBNull.问题是Convert.IsDBNull(reader["name"])在检查 DBNull之前首先调用reader["name"]DbDataReader中提取值。

Instead of Convert.IsDBNull , use DbDataReader.IsDBNull .而不是Convert.IsDBNull ,使用DbDataReader.IsDBNull I'd also use GetString() instead of GetValue().ToString() .我还会使用GetString()而不是GetValue().ToString()

string nam = reader.IsDBNull(reader.GetOrdinal("name")) ? "" : reader.GetString("name");
string password = reader.IsDBNull(reader.GetOrdinal("password")) ? "" : reader.GetString("password");

Like others commented, using a simple ORM, like Dapper, or a full ORM such as EF Core, will simplify and eliminate a lot of this code.就像其他人评论的那样,使用简单的 ORM(如 Dapper)或完整的 ORM(如 EF Core)将简化并消除大量此类代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.InvalidCastException:无法将对象从DBNull强制转换为其他类型 - System.InvalidCastException: Object cannot be cast from DBNull to other types MySqlConnection.Open() System.InvalidCastException: 对象无法从 DBNull 转换为其他类型 - MySqlConnection.Open() System.InvalidCastException: Object cannot be cast from DBNull to other types 当Checkbox值为null时。 程序抛出此错误“对象不能从DBNull强制转换为其他类型。” - When Checkbox value is null. Program throws this error“ Object cannot be cast from DBNull to other types.” 无法将对象从DBNull强制转换为其他类型。 读取器读取空值时出错 - Object cannot be cast from DBNull to other types. Error when a null value is read by the Reader 错误。 '对象不能从 DBNull 转换为其他类型。' C# 与方法 sum() - Error! 'Object cannot be cast from DBNull to other types.' C# with method sum() “无法将对象从DBNull强制转换为其他类型” - “Object cannot be cast from DBNull to other types” 无法将对象从DBNull强制转换为其他类型 - Object cannot be cast from DBNull to other types 无法将对象从DBNull强制转换为其他类型 - Object cannot be cast from DBNull to other types 无法将对象从DBNull强制转换为其他类型 - The Object cannot be cast from DBNull to other types Object 不能从 DBNull 转换为其他类型 - Object cannot be cast from DBNull to other types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM