日期:2014-05-16  浏览次数:20492 次

C#中数据库的更新和删除记录的两种实现方式

框图在上一篇文章中给出了,删除、更新和插入一样,也都有两种方式,一种是在数据源的编辑器中设定相应的方法来实现,另一种是自己写代码完成。

下面先给出更新的代码:

         test_dbDataSet.courseRow cro;
            test_dbDataSet.facultyRow fro;
            if ( (course.Text == "") || (facultyid.Text == "") || (this.name.Text == "") || (this.num.Text == ""))
                MessageBox.Show("有一项或者多项没有填写内容,请填写完毕后再提交!");
            else
            {

               ///第一种方式      这里更新都没有更新表的主键,如果要更新主键最好方法就是找到该记录,删除它,然后在插入一个新的记录。
                if (cbupdate.Text == "tableAdater.update")
                {

                    int f = facultyTableAdapter.Updatefaculty(this.name.Text, this.num.Text, this.facultyid.Text);
                    int c = courseTableAdapter.Updatecourse(this.course.Text, this.facultyid.Text);
                    if ((f > 0) && (c > 0))
                        MessageBox.Show("更新成功!");
                    else
                        MessageBox.Show("更新失败!");
                }

                ///第二种方式
                else
                {
                    string cid;
                    fro = test_dbDataSet.faculty.FindByfaculty_id(facultyid.Text);
                    fro = updatefacultydata(ref fro);
                    this.Validate();
                    facultyBindingSource1.EndEdit();
                    int f = facultyTableAdapter.Update(test_dbDataSet.faculty);

                   cid = courseTableAdapter.getcourseid_fid(facultyid.Text);