Trido
Trido

Reputation: 545

Validation method error

I have the following method to ensure that an entered username does not already exist.

protected void checkUsername(object source, ServerValidateEventArgs args)
{
    string connString = "Data Source=server;Initial Catalog=database;User Id=username;Password=password;";
    string cmdText = "SELECT COUNT(*) FROM igs_users WHERE username = @username";

    using(SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        using(SqlCommand cmd = new SqlCommand(cmdText, conn))
        {
            cmd.Parameters.AddWithValue("@username", username);
            Int32 count = (Int32)cmd.ExecuteScalar();

            args.IsValid = true;
        }
    }
}

When I run it, I get the following error.

System.ArgumentException was unhandled by user code HResult=-2147024809 Message=No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type. Source=System.Data

The debugger gives me this error for the below line.

Int32 count = (Int32)cmd.ExecuteScalar();

Any idea what's wrong with this code?

Upvotes: 1

Views: 111

Answers (1)

wintermute
wintermute

Reputation: 186

I would think it's the line

cmd.Parameters.AddWithValue("@username", username);

Is username a TextBox? If so, you should change the line to:

cmd.Parameters.AddWithValue("@username", username.Text);

The line as it currently stands attempts to bind the TextBox control itself to the @username parameter. The correction binds the text within the TextBox control to @username.

Upvotes: 4

Related Questions