必须声明用于填充 DataGridView 的标量变量 - SQL 参数

Must declare the scalar variable - SQL parameter for filling DataGridView

我发现了类似的问题,但 none 的答案对我有帮助或适用于我。

我正在使用 Visual Studio 2013,C# 和名为 T-SQL.

的数据库引擎

如果我用具体值替换参数,SQL 命令就可以正常工作。但是我需要那里的参数。

我收到这个错误:

Must declare the scalar variable "@Collection1".

这一行:

myydata.Fill(myytab);

无论我做什么,那个@Collection1就是不想被宣告。

string stringcommand = "select Name, Collection, Text from Card_List where Collection IN" +
                       "(select Shortcut from Collections where Collection Like @Collection1)";

SqlConnection myConnection = new SqlConnection(stringconnection);
SqlCommand myCommand = new SqlCommand(stringcommand, myConnection);

// Tried to declare parameter 5 times here, unsuccessfully
myCommand.Parameters.Add(new SqlParameter("Collection1", string1));
myCommand.Parameters.Add("@Collection1", SqlDbType.NVarChar).Value = string1;
myCommand.Parameters["@Collection1"].Value = string1;
myCommand.Parameters.AddWithValue("@Collection1", string1);
SqlParameter Param1 = myCommand.Parameters.Add("@Collection1", SqlDbType.NVarChar);
Param1.Value = string1;

SqlDataAdapter myydata = new SqlDataAdapter();
myydata.SelectCommand = new SqlCommand(stringcommand, myConnection);
myConnection.Open();
DataTable myytab = new DataTable();
myydata.Fill(myytab);
BindingSource bsour = new BindingSource();
bsour.DataSource = myytab;
dataGridView1.DataSource = bsour;
myydata.Update(myytab);
myConnection.Close();

您希望将您设置的 SqlCommand myCommand 用作 myydata.SelectCommand,例如:

myCommand.Parameters.Add(new SqlParameter("Collection1", string1));
myydata.SelectCommand = myCommand;

您使用 myydata.SelectCommand = new SqlCommand(stringcommand, myConnection); 的方式,该命令在命令中包含 @Collection1,但没有附加任何参数,您会收到 Must declare the scalar variable "@Collection1". 错误。