简体   繁体   English

如何在参数中分配默认值?

[英]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. 我下面的代码将显示来自Access数据库的数据到另一种形式的文本框中。

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 参数@Item没有默认值

But I already assigned the value of @Item in this line 但是我已经在这一行中分配了@Item的值

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

I found some mistakes, you are retrieving some items. 我发现了一些错误,您正在检索某些项目。 Then, Why you are using ExecuteNonquery() and some other parameters. 然后,为什么要使用ExecuteNonquery()和其他一些参数。 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. 确保items.ItemName1具有有效条目。 You can verify this by simply passing some values manually as 您可以通过简单地手动传递一些值来验证这一点

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

Try this one: 试试这个:

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

And why are you using this again after ExecuteNonQuery() ..? 又为什么在ExecuteNonQuery() ..之后再次使用它?

cmd.Parameters.AddWithValue("@ItemID", addorder.tbItemID.Text);
cmd.Parameters.AddWithValue("@ItemName", addorder.tbName.Text);
cmd.Parameters.AddWithValue("@ItemPrice", addorder.tbPrice.Text);
cmd.Parameters.Add(new OleDbParameter("item", OleDbType.VarChar, 32,  "Item").Value = items.ItemName1;
                   ^^^^^^^^^^^^^^^^^^

the point is to construct Parameter() 关键是构造Parameter()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM