//生成“课程”DatagridView private DataGridView CreatedgvCourse() { //生成page中的Datagridview DataGridView dgvCourse = new DataGridView(); dgvCourse.Name = "dgvCourse"; //设置该控件在代码中的Name dgvCourse.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //列宽度 dgvCourse.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //列高度 dgvCourse.SelectionMode = DataGridViewSelectionMode.FullRowSelect; //选中单元行的模式:整行选中 dgvCourse.AutoGenerateColumns = false; //关闭自动生成列 dgvCourse.ReadOnly = false; //关闭单元格上的编辑 dgvCourse.Dock = DockStyle.Fill; //编辑列 DataGridViewTextBoxColumn[] cols = { new DataGridViewTextBoxColumn() { HeaderText = "编号", DataPropertyName = "Id" }, new DataGridViewTextBoxColumn() { HeaderText = "课程名", DataPropertyName = "Name" }, new DataGridViewTextBoxColumn() { HeaderText = "所属专业编号", DataPropertyName = "Speciality_id" }, new DataGridViewTextBoxColumn() { HeaderText = "上课地点", DataPropertyName = "Room_name" }, new DataGridViewTextBoxColumn() { HeaderText = "学期", DataPropertyName = "Semester" } }; //dgv注册删除事件 dgvCourse.Columns.AddRange(cols); dgvCourse.CellContextMenuStripNeeded += new DataGridViewCellContextMenuStripNeededEventHandler((a, b) => { ContextMenuStrip rightMenu = new ContextMenuStrip(); //右键菜单 //注册删除事件 rightMenu.Items.Add("删除", null, new EventHandler((c, d) => { if (MessageBoxEx.Show("是否删除该课程??", "警告", MessageBoxButtons.OKCancel) != DialogResult.OK) { return; } CourseBLL bll_course = new CourseBLL(); int course_id = Convert.ToInt32(dgvCourse.Rows[b.RowIndex].Cells[0].Value); //得到班级Id bool result = bll_course.SoftDeleteById(course_id, frmMain.current_user.Id); MessageBoxEx.Show(result ? "删除成功!" : "删除失败,该数据不存在请重试!!"); (dgvCourse.DataSource as List <Course>).RemoveAll(model => { return(model.Id == course_id); }); })); dgvCourse.ContextMenuStrip = rightMenu; //dgvCourser加入右键菜单 }); return(dgvCourse); }