bhert
bhert

Reputation: 67

How to assign default value in a parameter?

I have the codes below that will display data from access database into textboxes of another form.

item items = new item();
Add_Order addorder = new Add_Order();
OleDbCommand cmd = new OleDbCommand("Select * from tblItems WHERE ItemName = @Item", connection);
cmd.Parameters.AddWithValue("@Item", items.ItemName1);
cmd.Connection = connection;
connection.Open();

cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("@ItemID", addorder.tbItemID.Text);
cmd.Parameters.AddWithValue("@ItemName", addorder.tbName.Text);
cmd.Parameters.AddWithValue("@ItemPrice", addorder.tbPrice.Text);
OleDbDataReader read = cmd.ExecuteReader();
while (read.Read())
{
    addorder.tbItemID.Text = read[0].ToString();
    addorder.tbName.Text = read[1].ToString();
    addorder.tbPrice.Text = read[2].ToString();
}
addorder.ShowDialog();
connection.Close();

the error says that

Parameter @Item has no default value

But I already assigned the value of @Item in this line

cmd.Parameters.AddWithValue("@Item", items.ItemName1);

Upvotes: 0

Views: 2003

Answers (3)

4pie0
4pie0

Reputation: 29724

cmd.Parameters.Add(new OleDbParameter("item", OleDbType.VarChar, 32,  "Item").Value = items.ItemName1;
                   ^^^^^^^^^^^^^^^^^^

the point is to construct Parameter()

Upvotes: 0

Linga
Linga

Reputation: 10553

I found some mistakes, you are retrieving some items. Then, Why you are using ExecuteNonquery() and some other parameters. Simply try this

cmd.Connection = connection;
connection.Open();
OleDbCommand cmd = new OleDbCommand("Select * from tblItems WHERE ItemName = @Item", connection);
cmd.Parameters.AddWithValue("@Item", items.ItemName1);

OleDbDataReader read = cmd.ExecuteReader();
while (read.Read())
{
addorder.tbItemID.Text = read[0].ToString();
addorder.tbName.Text = read[1].ToString();
addorder.tbPrice.Text = read[2].ToString();
}
connection.Close();

Make sure that items.ItemName1 has a valid entry. You can verify this by simply passing some values manually as

cmd.Parameters.AddWithValue("@Item", "some text");

Upvotes: 2

Vishal Suthar
Vishal Suthar

Reputation: 17194

Try this one:

cmd.Parameters.AddWithValue("@Item", OleDbType.VarChar).Value = items.ItemName1;

And why are you using this again after ExecuteNonQuery()..?

cmd.Parameters.AddWithValue("@ItemID", addorder.tbItemID.Text);
cmd.Parameters.AddWithValue("@ItemName", addorder.tbName.Text);
cmd.Parameters.AddWithValue("@ItemPrice", addorder.tbPrice.Text);

Upvotes: 1

Related Questions