系统。出现InvalidOperationException

时间:2017-04-08 17:33:41

标签: c# mysql

我正在尝试使用登录系统制作程序 我是新手,但我已经连续工作了8个小时试图解决这个问题。 这是我得到的错误代码

+ ServerVersion 'con.ServerVersion' threw an exception of type 'System.InvalidOperationException'   string {System.InvalidOperationException}

这是我的代码

    private void LogB_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=Myip;user id=MyId;database=MyDb;password=MyPw;persistsecurityinfo=True");
        SqlDataAdapter sda = new SqlDataAdapter("Select * From login where navn='"+ TULog.Text + "' and pw='" + TPLog.Text + "'",con);

        try
        {

            con.Open();


        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.ToString());
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }
}
}

对不起如果这看起来像废话,但我是一个正在努力学习的人:p

1 个答案:

答案 0 :(得分:1)

This exception is telling you that there was an attempt to access the con.ServerVersion property while the SqlConnection was closed.

From MSDN on the SqlConnection.ServerVersion property:

InvalidOperationException - The connection is closed. ServerVersion was called while the returned Task was not completed and the connection was not opened after a call to OpenAsync.

The code you show above does not show a call to this property, you must be doing so somewhere else. Regardless, the connection needs to be open prior to doing so.