Animesh Ghosh
Animesh Ghosh

Reputation: 341

Access Database error:: “No value given for one or more required parameters.”

I have a datagridview. In this DGV first colum is a combobox column. I want to make, when this combobox value is selected next fild will be filled automatically from database. But there shows a error.

No value given for one or more required parameters on OleDbDataReader dr1 = cmd1.ExecuteReader();

I post the code. Please help me.

OleDbConnection con = new OleDbConnection(conn);
con.Open();

for (int i = 0; i < dgv.Rows.Count; i++)
{

    string query = "select Description from General where AccCode='" +
        dgv.Rows[i].Cells[0].Value +
        "' and conpanyID='" +
        label1.Text + "'";
    OleDbCommand cmd1 = new OleDbCommand(query, con);
    //OleDbDataAdapter daBranchName = new OleDbDataAdapter(cmd);
    OleDbDataReader dr1 = cmd1.ExecuteReader();
    while (dr1.Read())
    {
        dgv.Rows[i].Cells[1].Value = dr1["Description"].ToString();
    }
}
con.Close();

Upvotes: 1

Views: 16552

Answers (3)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

This kind of string concatenations are open for SQL Injection attacks.

Use parameterized queries instead.

string query = "select [Description] from [General] where AccCode= ? and conpanyID= ?";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("@acc", dgv.Rows[i].Cells[0].Value);
cmd1.Parameters.AddWithValue("@ID", label1.Text);

As HansUp pointed, Description and General are reserved keywords. Use them with square brackets like [Description] and [General]

Upvotes: 6

Damith
Damith

Reputation: 63065

Use Parameters, otherwise it will open for sql injection attacks.

string query = "select [Description] from General where AccCode=? and conpanyID=?";

now you can set parameters

cmd.Parameters.AddWithValue("@p1", val1);
cmd.Parameters.AddWithValue("@p2", val2);

Upvotes: 2

LarsTech
LarsTech

Reputation: 81620

As suggested, use parameterized queries.

As far as the error is concerned, I'm guessing this field name is wrong:

conpanyID=

should be:

companyID=

Upvotes: 3

Related Questions