NorthwindDBDataContext dc = new NorthwindDBDataContext(); protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; Bind(); } /// <summary> /// 绑定数据 /// </summary> private void Bind() { GridView1.DataSource = dc.Users; GridView1.DataBind(); } /// <summary> /// 添加 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { //把需要的值存起来 string name = TextBox1.Text; string pass = TextBox2.Text; bool sex = CheckBox1.Checked; Users user = new Users() { UserName = name, UserPwd = pass, Sex = sex }; //初始化一个用户类 dc.Users.InsertOnSubmit(user); //提交数据 //List<Users> list = new List<Users>() { user };//生成一个用户集合 //dc.Users.InsertAllOnSubmit(list); //提交数据 dc.SubmitChanges(); //对数据库进行修改 Bind(); } /// <summary> /// 删除 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { //把需要删除的ID找到 string id = GridView1.DataKeys[e.RowIndex].Value.ToString(); //ID进行过绑定 ① var result = from u in dc.Users where u.ID.ToString() == id select u; //把需要删除的行先找出来 dc.Users.DeleteAllOnSubmit(result); //删除多行 result 就是一个集合 //dc.Users.DeleteOnSubmit(result.First()); 删除单行 dc.SubmitChanges(); //跟新数据库 Bind(); } ①=var result = dc.Users.Where((x) => x.ID.ToString() == id); //相当于LINQ语句查询 确定是那张表where里面接Lambda表达式
修改一般都是拿到数据到别的页面进行修改,然后再提交到数据库 更新超链接定位此网页 tt.aspx?id={0} 把ID传过来
NorthwindDBDataContext dc = new NorthwindDBDataContext(); protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; string id = Request.QueryString["id"].ToString(); //拿到需要修改行的ID Users user = dc.Users.Where((x) => x.ID.ToString() == id).First(); //拿到需要修改的那行数据 TextBox1.Text = user.UserName; TextBox2.Text = user.UserPwd; CheckBox1.Checked = user.Sex; } protected void Button1_Click(object sender, EventArgs e) { string id = Request.QueryString["id"].ToString(); Users user = dc.Users.Where((x) => x.ID.ToString() == id).First(); //找到需要修改行,进行修改 user.UserName = TextBox1.Text; user.UserPwd = TextBox2.Text; user.Sex = CheckBox1.Checked; dc.SubmitChanges(); Response.Redirect("test.aspx"); //再回原来的页面 }