【发布时间】:2013-12-27 20:40:36
【问题描述】:
当我尝试更新时,我无法弄清楚给定代码的确切问题。
protected void UpdateService(object sender, GridViewUpdateEventArgs e)
{
int ServiceId = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblServiceID")).Text);
string ServiceName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtService")).Text;
decimal Rate = Convert.ToDecimal(((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtRate")).Text);
string ParentService = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlParentService")).SelectedItem.Text;
string GrandParentService = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlGrandParentService")).SelectedItem.Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Service set ServiceName=@ServiceName,Rate=@Rate,"+
"ParentService=@ParentService,GrandParentService=@GrandParentService "+
"where ServiceId = @ServiceId;" +
"select ServiceId,GrandParentService,ParentService,ServiceName,Rate from Service";
cmd.Parameters.Add("@ServiceName", SqlDbType.VarChar).Value = ServiceName;
cmd.Parameters.Add("@Rate", SqlDbType.Decimal).Value = Rate;
cmd.Parameters.Add("@ParentService", SqlDbType.VarChar).Value = ParentService;
cmd.Parameters.Add("@GrandParentService", SqlDbType.VarChar).Value = GrandParentService;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt); //Error "Must declare the scalar variable "@ServiceId".
return dt;
}
我收到一条错误消息“必须在更新时声明标量变量“@ServiceId”。“ServiceId”是表的主键。
请帮助我。提前致谢。
【问题讨论】:
-
您的
SqlCommand中有一个@ServiceId,但您从未使用Parameters.Add()方法将其添加为参数。 -
ServiceId 是我的主键。
-
但是就像 Soner 说的,您仍然需要传递 ServiceId 值,否则如果您在
WHERE子句中没有传递任何内容,您的 SQL 命令将如何知道要更新的行? -
非常感谢....解决了。
标签: c# asp.net sql-server c#-4.0