向参数添加值时的System.NullReferenceException

时间:2016-12-18 07:15:55

标签: c# mysql asp.net

所以我试着写一个方法来检查用户输入的用户名是否存在于MySQL数据库中。但是我遇到了这个例外:

System.NullReferenceException: Object reference not set to an instance of an object.

指向这行代码:

cmd.Parameters.AddWithValue("?username", usernameTextBox.Text);

以下是checkusername方法:

String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "SELECT count(*) FROM webappdemo.userregistration WHERE username = ?username";
cmd.Parameters.AddWithValue("?username", usernameTextBox.Text);
cmd = new MySqlCommand(queryStr, conn);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
    //username taken
    doesuserexist = true;
    LabelUsername.Text = "Username Exists";
}
else
{
    //username good
    doesuserexist = false;
    LabelUsername.Text = "";
}

0 个答案:

没有答案