Asp.net网格视图批量更新所有单元格
本文关键字:更新 单元格 net 网格 视图 Asp | 更新日期: 2023-09-27 18:17:37
我使用asp.net网格视图从我的sql数据表加载数据。我可以成功加载数据。
Sql Table design:3 cloumns:位置,Firstname、LastName
Location是主键。
设计: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();
}
Exception:"必须声明标量变量"@Location"。"
您需要为SqlCommand对象添加一个名为"@Location"的参数。您提到Location是网格中的一列——您可以从列中读取值(类似于获取姓和名的方式),或者您可以指定"Location"作为数据键,并从网格的DataKeys属性中获取它。
我会看ASP。. NET Real World Controls项目。它允许批量编辑,并且它足够智能,只更新已更改的行。
//@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);//添加declare cmd.Parameters。AddWithValue("@Location someLocationValue.Trim ());
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();
}