日期:2014-05-18  浏览次数:20437 次

关于GridView空间的更新问题
Page_Load代码
  SqlCommand cmd = new SqlCommand("select * from Teacher",conn);
  SqlDataAdapter da = new SqlDataAdapter(cmd);
  DataTable dt = new DataTable();
  da.Fill(dt);
  GridView2.DataSource = dt;
  GridView2.DataBind();
  this.GridView2.DataKeyNames = new string[] { "TNO" };
Html代码
  <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" 
  onrowediting="GridView2_RowEditing" onrowupdating="GridView2_RowUpdating" 
  Width="586px" onrowcancelingedit="GridView2_RowCancelingEdit" 
  onrowdeleting="GridView2_RowDeleting">
  <Columns>
  <asp:BoundField HeaderText="教师ID" DataField="TNO"/>
  <asp:BoundField HeaderText="教师姓名" DataField="TNAME"/>
  <asp:BoundField HeaderText="性别" DataField="TSEX" />
  <asp:BoundField HeaderText="生日" DataField="TBIRTHDAY" />
  <asp:BoundField HeaderText="职称" DataField="PROF" />
  <asp:BoundField HeaderText="所属系部" DataField="DEPART" />
  <asp:CommandField ShowEditButton="True" />
  <asp:CommandField ShowDeleteButton="True" />
  </Columns>
  </asp:GridView>
后台代码
  protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
   
  string TID = GridView2.DataKeys[e.RowIndex].Value.ToString();
  string tName = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();
  string sex = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();
  string birthday = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
  DateTime dt =Convert.ToDateTime(birthday);
  string status = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString();
  string depart = ((TextBox)(GridView2.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString();
  string sql = "update teacher set Tname='"+tName.Trim()+"',tsex='"+sex.Trim()+"',tbirthday='"+DateTime.Now+"',prof='"+status.Trim()+"',depart='"+depart.Trim()+"' where TNO='"+TID+"'";
  SqlCommand cmd = new SqlCommand(sql,conn);
  conn.Open();
   
  cmd.ExecuteNonQuery();
   
   
  Response.Write("修改成功!");
  conn.Close();
  cmd.Dispose();
  GridView2.EditIndex = -1;
  Bonding();



  }
  public void Bonding()
  {
  SqlCommand cmd = new SqlCommand("select * from Teacher", conn);
  SqlDataAdapter da = new SqlDataAdapter(cmd);
  DataTable dt = new DataTable();
  DataSet ds = new DataSet();
  da.Fill(dt);
  GridView2.DataSource = dt;
  GridView2.DataBind();
  this.GridView2.DataKeyNames = new string[] { "TNO" };
 
  }
在执行更新的时候没有报错,但是只能获得TID和dt