Command对象修改数据有问题
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.bind();
}
}
public SqlConnection GetConnection()
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection myConn = new SqlConnection(myStr);
return myConn;
}
protected void bind()
{
SqlConnection myConn = GetConnection();
myConn.Open();
string sqlStr = "select * from tb_Class ";
SqlDataAdapter myDa = new SqlDataAdapter(sqlStr, myConn);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
GridView1.DataSource = myDs;
GridView1.DataKeyNames = new string[] { "ClassID" };
GridView1.DataBind();
myDa.Dispose();
myDs.Dispose();
myConn.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;这句什么意思?
this.bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int ClassID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());这句是不是设置成当前选中的索引值?
string CName = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();这句什么意思?
string sqlStr = "update tb_Class set ClassName='" + CName + "' where ClassID=" + ClassID;
SqlConnection myConn = GetConnection();
myConn.Open();
SqlCommand myCmd = new SqlCommand(sqlStr, myConn);
myCmd.ExecuteNonQuery();
myCmd.Dispose();
myConn.Close();
GridView1.EditIndex = -1;为什么这里有减1?
this.bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;为什么这里有减1?
this.bind();
}
------解决方案--------------------GridView1.EditIndex = e.NewEditIndex;这句是获取当前选中的要编辑行的索引。
int ClassID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());这句是根据索引值获取classID,
string CName = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();这句是获取CName,
GridView1.EditIndex = -1;这句是把GridView1的索引值置空,
------解决方案--------------------GridView1.EditIndex = e.NewEditIndex;是获取当前选中行的索引,进行编辑状态操作。
int ClassID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());这是根据索引获取此行主键ClassID 的值
string CName = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();这是根据索引获取此行CName 的值
GridView1.EditIndex = -1;取消编辑状态 获取或设置要编辑的行的索引。默认值为 -1,指示没有正在编辑的行从0开始索引。
------解决方案--------------------上面都已經說很清楚了。