【ASP】GridView相关事件操作
描述:对GridView分页,选择,增删改查等操作
绑定GridView,并且显示数据 public void BindGridView() { SqlConnection con = new SqlConnection("server=.;database=student;integrated security=true"); SqlDataAdapter da = new SqlDataAdapter("select *from stuInfo",con); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds; GridView1.Caption = "学生信息表"; //显示表头 GridView1.DataKeyNames = new String[] {"sno"}; //定义主键 GridView1.DataBind(); } 显示详细信息 protected void GridView1_SelectedIndexChanging1(object sender, GridViewSelectEventArgs e) { string no = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString(); SqlConnection con = new SqlConnection("server=.;database=student;integrated security=true"); SqlDataAdapter da = new SqlDataAdapter("select *from stuInfo where sno='" + no + "'", con); DataSet ds = new DataSet(); da.Fill(ds); GridView2.DataSource = ds; GridView2.Caption = "学生详细信息表"; GridView2.DataBind(); } 实现分页功能 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; this.BindGridView(); } 实现编辑功能 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; this.BindGridView(); } 实现取消编辑功能 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; this.BindGridView(); } 实现更新数据功能 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { try { string no = GridView1.DataKeys[e.RowIndex].Value.ToString(); string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text; SqlConnection con = new SqlConnection("server=.;database=student;integrated security=true"); con.Open(); SqlCommand cmd = new SqlCommand("update stuInfo set sname='" + name + "' where sno='" + no + "'",con); cmd.ExecuteNonQuery(); con.Close(); GridView1.EditIndex = -1; this.BindGridView(); } catch (Exception e1) { Response.Write(e1); } } } }
作者:白宁超,工学硕士,现工作于四川省计算机研究院,研究方向是自然语言处理和机器学习。曾参与国家自然基金项目和四川省科技支撑计划等多个省级项目。著有《自然语言处理理论与实战》一书。 自然语言处理与机器学习技术交流群号:436303759 。
出处:http://www.cnblogs.com/baiboy/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。