using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class _Default : System.Web.UI.Page { //声明静态的数据操作对象 protected static DemoDbDataContext context = new DemoDbDataContext("Data Source=.;Initial Catalog=DemoDb;Integrated Security=True"); protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { //页面首次加载时 获取所有员工数据 this.BindGridView(); } } private void BindGridView() { //获取所有员工数据 this.GridView1.DataSource = from emp in context.Employee1 select emp; //数据绑定 this.GridView1.DataBind(); } protected void btnInert_Click(object sender, EventArgs e) { //添加员工信息 Employee1 emp = new Employee1(); emp.EmpName = this.txtEmpName.Text; emp.EmpAge = Convert.ToInt32(this.txtEmpAge.Text); emp.EmpSex = this.rblSex.SelectedItem.Text; emp.Sales = 0; //将员工实体对象状态更改为添加状态 context.Employee1.InsertOnSubmit(emp); //提交数据更改 context.SubmitChanges(); this.BindGridView(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { this.GridView1.EditIndex = e.NewEditIndex; this.BindGridView(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { //获取被删除的员工数据对象 Employee1 de = (from emp in context.Employee1 where emp.EmpID == Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value) select emp).Single(); //将员工实体对象状态更改为删除状态 context.Employee1.DeleteOnSubmit(de); //提交数据更改 context.SubmitChanges(); this.BindGridView(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { //获取需要被更新的员工对象 Employee1 de = (from emp in context.Employee1 where emp.EmpID == Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value) select emp).Single(); //修改相应数据 de.EmpAge = Convert.ToInt32((this.GridView1.Rows[e.RowIndex].FindControl("txtEmpAge") as TextBox).Text); de.EmpName = (this.GridView1.Rows[e.RowIndex].FindControl("txtEmpName") as TextBox).Text; de.EmpSex = (this.GridView1.Rows[e.RowIndex].FindControl("rblEmpSex") as RadioButtonList).SelectedItem.Text; de.Sales = 0; //提交数据更改 context.SubmitChanges(); this.GridView1.EditIndex = -1; this.BindGridView(); } }