Skip to content
Advertisement

Why am I getting insufficient parameters supplied to the command error?

I have trying to read a database and display it into a datagridview, but I keep getting the error, using Windows Forms and SQLite:

private void nameSearch()
{
    using (SQLiteCommand cmd = connAccount.CreateCommand())
    {
        connAccount.Open();
        try
        {
            connAccount = new SQLiteConnection(dbConnection.source);

            cmd.CommandText = @"SELECT accid, account.custid, customer.title,
                                customer.firstname || ' ' || customer.lastname AS Name,
                                product.isaname AS ProductName, balance,
                                accrued, active
                                FROM account INNER JOIN customer ON customer.custid = account.custid
                                INNER JOIN product ON product.prodid = account.prodid
                                WHERE Name = @setName";

            cmd.Parameters.AddWithValue("@setName", txt_name.Text);
            cmd.ExecuteNonQuery();

            da_Accounts = new SQLiteDataAdapter(cmd.CommandText, connAccount);
            dt_Accounts = new DataTable();
            da_Accounts.Fill(dt_Accounts);
            dgv_Account.DataSource = dt_Accounts;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

That’s the code I’m using, but what is the issue?

I have tried removing the concatenation, and I’ve tried changing the parameters method too:

cmd.Parameters.Add("@setName", DbType.String).Value = txt_name.Text;

I tried with and without the executenonquery() each time.

Advertisement

Answer

I have finally got it working. The issue was with the line:

cmd.Parameters.AddWithValue("@setName", txt_name.Text);

I had to delete this line and add the parameters to the actual adapter. And now it’s working.

try
{
    conn = new SQLiteConnection(dbConnection.source);

    cmd.CommandText = @"SELECT * FROM customer WHERE lastname = @Name";

    da_Customer = new SQLiteDataAdapter(cmd.CommandText, conn);
    da_Customer.SelectCommand.Parameters.AddWithValue("Name", txt_name.Text);
    dt_Customer = new DataTable();
    da_Customer.Fill(dt_Customer);
    dgv_customer.DataSource = dt_Customer;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement