我正在使用asp.net网格视图从我的sql数据表加载数据。我能够成功加载数据。
Sql Table Desgin: 3 cloumns:位置,名字,姓氏
位置是主键。
设计:
Aspxpage有一个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“。”
答案 0 :(得分:3)
您需要向名为“@Location”的SqlCommand对象添加参数。您提到Location是网格中的一列 - 您可以从列中读取值(类似于获取名字和姓氏值的方式),也可以指定“Location”作为数据键,并从网格的DataKeys属性中获取它。
我会看看Codeplex上的ASP.NET Real World Controls项目。它允许批量编辑,并且足够智能,只能更新已更改的行。
答案 1 :(得分:2)
//@Location means that the Insert / Update expects that field to be passed in / added //to your cmd.Parameters where are you adding @Location...?
//查看你有这个WHERE Location = @Location的行,myConnection); //添加声明cmd.Parameters.AddWithValue(“@ Location”,someLocationValue.Trim());
答案 2 :(得分:2)
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;
TextBox txtLanguage3 = row.FindControl("txtLocation") 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());
cmd.Parameters.AddWithValue(“@ Location”,txtLocation.Text.Trim());
myConnection.Open();
cmd.ExecuteNonQuery();
gvusers.EditIndex = -1;
DataBind();
}