Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

c# - 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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...