查看文章 |
GridView的选择,取消,编辑,删除,更新 所对应的按钮
2008-04-20 22:22
GriedView中的列索引号是从1开始的,而行的索引是从0开始的,本来以为列的索引也是0开始,就这点小误区让我搞了好一会才找到问题的根点.以下是详细代码 public partial class tw2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { this.createdb(); } } private void createdb() { SqlConnection cn = new SqlConnection("server=.;database=zhang;uid=sa;pwd=410"); //(Data Source =服务器;Initial Catalog=数据库;Integrated Security=True")本地用户登录 SqlDataAdapter adp = new SqlDataAdapter(); adp.SelectCommand = new SqlCommand("select * from chang", cn); DataSet ds = new DataSet(); adp.Fill(ds, "chang"); this.GridView1.DataKeyNames = new string[] { "changid" }; //定义主键 this.GridView1.DataSource = ds.Tables[0].DefaultView; this.GridView1.DataBind(); cn.Close(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) //取消按钮 { GridView1.EditIndex = -1; this.createdb(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) //编辑按钮 { GridView1.EditIndex = e.NewEditIndex; this.createdb(); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) //选择按钮 { int id = Convert.ToInt32(e.CommandArgument); //取行索引号 string txt = GridView1.DataKeys[id].Value.ToString(); //取主键的值 Response.Write(txt); // this.createdb(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) //删除按钮 { SqlConnection cn = new SqlConnection("server=.;database=zhang;uid=sa;pwd=410"); cn.Open(); SqlCommand cm=new SqlCommand("delete from chang where changid=" +GridView1.DataKeys[e.RowIndex].Value,cn); //e.RowIndex取本行索引号, cm.ExecuteNonQuery(); cn.Close(); GridView1.EditIndex = -1; this.createdb(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) //更新按钮 { GridViewRow row = GridView1.Rows[e.RowIndex]; TextBox box = (TextBox)row.Cells[2].Controls[0]; Response.Write(box.Text); try { SqlConnection cn = new SqlConnection("server=.;database=zhang;uid=sa;pwd=410"); cn.Open(); SqlCommand cm = new SqlCommand("update chang set chang1='" + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',chang2='" + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where changid=" + GridView1.DataKeys[e.RowIndex].Value, cn); //列的编号是从1,这里更新的是第二列和第三列所以cell[2],cell[3],而行的索引是从0开始的 cm.ExecuteNonQuery(); GridView1.EditIndex = -1; this.createdb(); cn.Close(); } catch (Exception exc) { Response.Write(exc.Message); } } } |
最近读者: