Search code examples
c#sqlstored-proceduresargumentexceptionionic-zip

ArgumentException


I am making a simple Login Form and getting the following Exception

ArgumentException was caught. No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.

Here is the C# code

        SqlConnection con = new SqlConnection("Data source=.;Initial catalog=InvoiceSystem;user id =sa;password=rfm");
        SqlCommand cmd = new SqlCommand("spLogin", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p1 = new SqlParameter("username", txtUsername);
        SqlParameter p2 = new SqlParameter("password", txtPassword);
        cmd.Parameters.Add(p1);
        cmd.Parameters.Add(p2);
        try
        {
            con.Open();
            SqlDataReader rd = cmd.ExecuteReader();
            if (rd.HasRows)
            {
                rd.Read();
                Response.Redirect("Default.aspx");
            }
            else
            {
                Response.Write("<script>alert('Invalid Username/Password')</script>");
            }
        }
        catch{

        }

Solution

  • Your trying to send TextBox objects to the stored procedure:

    SqlParameter p1 = new SqlParameter("username", txtUsername);
    SqlParameter p2 = new SqlParameter("password", txtPassword);
    

    It doesn't know what to do with those objects. Instead, just send the text contained in those text boxes:

    SqlParameter p1 = new SqlParameter("username", txtUsername.Text);
    SqlParameter p2 = new SqlParameter("password", txtPassword.Text);