可能是学习能力有限吧,我从昨晚到今天,累积起来起码五六个小时,才终于弄懂了这个Gridview的编辑。毕竟找来的代码都是没有注释和说明的。
我想记录下来,也希望后来的新丁能少走弯路。
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } private void BindData() { string sql = string.Format("select * from Student"); DataTable dt = SqlHelper.ExctuteDataTable(sql); GridView1.DataSource = dt; GridView1.GridLines = GridLines.Both; GridView1.RowStyle.HorizontalAlign = HorizontalAlign.Center;//单元格文字居中 GridView1.DataBind(); GridView1.EditRowStyle.ForeColor = Color.Red; } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindData(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { /*先获得所要编辑的行的第0号单元格里的第一个子控件,转成TextBox类型然后取值*/ int Sid = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString().Trim()); /*FindControl里的参数填控件的id,但我们需要先获取这个id,所以不推荐这种用法。*/ //string Sname = (GridView1.Rows[e.RowIndex].Cells[0].FindControl("Sname") as TextBox).Text; string Sname = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString().Trim(); string Sage = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString().Trim(); string Sphone = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString().Trim(); string Spwd = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString().Trim(); string sql = string.Format("update Student set Sid={0},Sname='{1}',Sage='{2}',Sphone='{3}',Spwd='{4}'where Sid={5}", Sid, Sname, Sage, Sphone, Spwd, int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString())); SqlHelper.ExecuteNonQuery(sql); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; BindData(); }