我將多個項目插入到表格中,基於從下拉列表中的選擇。當我從下拉一個項目下來,然後一切工作正常,但是當我選擇多個項目,然後我得到這個錯誤變量名稱'@VarName'已被聲明問題
The variable name '@CompName' has already been declared. Variable names must be unique within a query batch or stored procedure.
我到底做錯了什麼?在這裏感謝 是我的代碼
protected void DV_Test_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
foreach (ListItem listItem in cblCustomerList.Items)
{
if (listItem.Selected)
{
string Name= listItem.Value;
sqlcon.Open();
string CompName= ((TextBox)DV_Test.FindControl("txtCompName")).Text.ToString();
string Num = ((TextBox)DV_Test.FindControl("txtNum")).Text.ToString();
SqlCommand cmd = new SqlCommand("select CompNamefrom MyTable where CompName= '" + CompName+ "' and Num = '" + Num + "' and Name= '" + Name+ "' ", sqlcon);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblmsg.Text = "Not Valid";
}
else
{
dr.Close();
sqlcmd.CommandText = "INSERT INTO MyTable(CompName, Num, Name) VALUES(@CompName, @Num, @Name)";
sqlcmd.Parameters.Add("@CompName", SqlDbType.VarChar).Value = CompName;
sqlcmd.Parameters.Add("@Num", SqlDbType.VarChar).Value = Num;
sqlcmd.Connection = sqlcon;
sqlcmd.ExecuteNonQuery();
DV_Test.ChangeMode(DetailsViewMode.Insert);
sqlcon.Close();
}
sqlcon.Close();
}
}
}
您還應該清理您的輸入並在該select語句中使用參數。 – MikeSmithDev