Ecburt
Ecburt

Reputation: 125

Trying to insert data to database in c# forms but getting this error message when insert button is hit. Parameter not supplied

Connecting my program to the database but running into this problem.

Error message:

The parameterized query '@first_name nvarchar(1), @last_name nvarchar(1), @email nvarchar(' expects the parameter '@username', which is not supplied.

Absolutely lost not really sure what the error message is saying.

Here's my code to insert the data into SQL Server database tables. Any advice is appreciated.

public bool Insert(userBLL u)
{
    bool Success = false;

    SqlConnection conn = new SqlConnection(myconnstrng);

    try
    {
        String sql = "INSERT INTO tbl_users (first_name, last_name, email, username, password, contact, address, gender, user_type, added_date, added_by) VALUES (@first_name, @last_name, @email, @username, @password, @contact, @address, @gender, @user_type, @added_date, @added_by)";

        SqlCommand cmd = new SqlCommand(sql, conn);

        cmd.Parameters.AddWithValue("@first_name", u.first_name);
        cmd.Parameters.AddWithValue("@last_name", u.last_name);
        cmd.Parameters.AddWithValue("@email", u.email);
        cmd.Parameters.AddWithValue("@username", u.username);
        cmd.Parameters.AddWithValue("@password", u.password);
        cmd.Parameters.AddWithValue("@contact", u.contact);
        cmd.Parameters.AddWithValue("@address", u.address);
        cmd.Parameters.AddWithValue("@gender", u.gender);
        cmd.Parameters.AddWithValue("@user_type", u.user_type);
        cmd.Parameters.AddWithValue("@added_date", u.added_date);
        cmd.Parameters.AddWithValue("@added_by", u.added_by);

        conn.Open();

        int rows = cmd.ExecuteNonQuery();

        // value of rows will be greater than 0 or else
        if (rows > 0)
        {
            Success = true; 
        }
        else
        {
            Success = false;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        conn.Close();
    }

    return Success;
}

Upvotes: 0

Views: 300

Answers (2)

thevinaychoudhary
thevinaychoudhary

Reputation: 393

After observing your code, In region(#region Insert data to database) that you shared, I think there was no problem in your code.

Make sure userBLL object is not null that you passed in function Insert. So debug your code one more time.

Upvotes: 1

Apoorva Asthana
Apoorva Asthana

Reputation: 76

By observing your code the only reason for this error looks like the userbill object has null value for username . So debug it one time and then share

Upvotes: 0

Related Questions