【发布时间】:2011-12-13 14:33:56
【问题描述】:
我正在使用 asp.net 网格视图从我的 sql 数据表中加载数据。我能够成功加载数据。
Sql 表设计: 3 列:位置、名字、姓氏
位置是主键。
设计:
Aspxpage 有一个gridview,底部有两个按钮:
- 编辑
- 保存
当用户点击编辑按钮时,gridview 中的所有单元格都可以编辑,以便用户可以编辑和保存值。
我的问题出现在保存按钮上,我无法将编辑后的数据保存回 SQL。
这是点击保存按钮的代码:
protected void btnSave_Click(object sender, EventArgs e)
{
int RowIndex=0;
GridViewRow row = (GridViewRow)gvres.Rows[RowIndex];
TextBox txtLanguage1 = row.FindControl("txtFName") as TextBox;
TextBox txtLanguage2 = row.FindControl("txtLName") as TextBox;
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE UsersTable SET FirstName = @FirstName, LastName = @LastName WHERE Location = @Location", myConnection);
cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim());
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
gvusers.EditIndex = -1;
DataBind();
}
例外:“必须声明标量变量“@Location”。”
【问题讨论】:
-
@Location 意味着插入/更新期望该字段被传递/添加到您的 cmd.Parameters 你在哪里添加@Location...?看看你有这个 WHERE Location = @Location", myConnection); 添加/声明 cmd.Parameters.AddWithValue("@Location", someLocationValue.Trim());
-
RowIndex 变量被硬编码为 0,因此只会更新第一行。如果整个网格只有 1 个保存按钮,那将是一个问题。
-
是的,这就是我现在发现的。它只更新第一行..那么我如何遍历所有行并更新。