用一个sqldatasource作为数据源,让gridview来指向它之后,启用了编辑和删除功能,这时是可以正常使用的。但如果在编辑列中,让其中的一个列不显示后,这时为什么 gridview的删除功能就不起作用了,按删除按钮不删数据了。如果在gridview的RowDeleting事件中:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView1.DataKeyNames = new string[] { "did" }; SqlConnection con = DB.createcon();
con.Open();
SqlCommand cmd = new SqlCommand("delete from dongtai where did=" + this.GridView1.DataKeys[e.RowIndex].Value, con);
cmd.ExecuteNonQuery();
this.GridView1.DataSourceID = "SqlDataSource1";
this.GridView1.DataBind();
}
这时,按删除按钮是可以删除了,但点编辑按钮时,可以显示出文本框,改完数据后,再点更新,怎么数据不改呢?汗!
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView1.DataKeyNames = new string[] { "did" }; SqlConnection con = DB.createcon();
con.Open();
SqlCommand cmd = new SqlCommand("delete from dongtai where did=" + this.GridView1.DataKeys[e.RowIndex].Value, con);
cmd.ExecuteNonQuery();
this.GridView1.DataSourceID = "SqlDataSource1";
this.GridView1.DataBind();
}
这时,按删除按钮是可以删除了,但点编辑按钮时,可以显示出文本框,改完数据后,再点更新,怎么数据不改呢?汗!
编辑使用UpdateCommand
UpdateParametersgridview编辑
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex =e.NewEditIndex;
BindData();
}
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
gv.EditIndex = e.RowIndex;
int id = int.Parse(gv.DataKeys[e.RowIndex].Value.ToString());
}
/// 修改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
Bind();
} /// <summary>
/// 更新
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GetConnection"].ToString());
int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
string sqlstr = "update Product_Category set name=@name,pid=@pid,[goto]=@goto where id="+id;
SqlCommand cmd = new SqlCommand(sqlstr,con);
cmd.CommandType = CommandType.Text;
try
{
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.Trim();
cmd.Parameters.Add("@pid", SqlDbType.Int).Value = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.Trim());
cmd.Parameters.Add("@goto", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.Trim();
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd.ExecuteNonQuery();
}
catch { }
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
GridView1.EditIndex = -1;
Bind(); }
另外在前台,把不需要编辑的列加上属性ReadOnly="True" 这列就不会被编辑了