课程优化终于完成了!!!非常感谢曹学亮的鼎力相助!!!
窗体上多选按钮可以让用户一次选择多个科目,然后点击"==>>"按钮,科目就被选入了右侧的listbox,同时写入数据库数据,删除同理,最后点击确认,退出课程设置。
看下代码:
【1】全部添加按钮
Private Sub cmdaddall_Click() Dim e As Integer Dim f As Integer For e = 0 To listAllcourse.ListCount - 1 Step 1 '添加选中科目 If listAllcourse.Selected(e) = True Then listSelectCourse.AddItem listAllcourse.List(e) End If Next e Call shanchu '自定义过程,删除重复的课程 MsgBox "课程添加成功!", vbOKOnly + vbInformation, "提示" '写入数据库,更新数据库 txtSQL = "select * from gradecourse_Info where grade='" & Trim(comboGrade.Text) & "'" Set mrc = ExecuteSQL(txtSQL, MsgText) If mrc.EOF Then For i = 1 To listSelectCourse.ListCount mrc.AddNew mrc.Fields(0) = comboGrade.Text mrc.Fields(1) = listSelectCourse.List(i - 1) mrc.Update Next i mrc.Close MsgBox "该年级的课程设置成功!", vbOKOnly + vbInformation, "提示" Else mrc.Close txtSQL = "DELETE from gradecourse_Info where grade='" & Trim(comboGrade.Text) & "'" Set mrc = ExecuteSQL(txtSQL, MsgText) txtSQL = "select * from gradecourse_Info" Set mrc = ExecuteSQL(txtSQL, MsgText) For i = 1 To listSelectCourse.ListCount mrc.AddNew mrc.Fields(0) = comboGrade.Text mrc.Fields(1) = listSelectCourse.List(i - 1) mrc.Update Next i mrc.Close MsgBox "该年级的课程设置成功!", vbOKOnly + vbInformation, "提示" End If End Sub
相比上面“全部添加按钮”写入数据库的代码,这个按钮的写入数据库代码非常简单有效,上面的代码还可以优化,就是右侧课程在前端的listbox控件正确添加完成后,后台sql server先删除数据库中对应年级的全部课程数据,重新写入该年级的所选科目,也就是下面的代码
Private Sub cmddeleteall_Click() Dim mrc As ADODB.Recordset For g = listSelectCourse.ListCount - 1 To 0 Step -1 If listSelectCourse.Selected(g) = True Then listSelectCourse.RemoveItem g End If Next g Call shanchuleft txtSQL = "DELETE from gradecourse_Info where grade='" & Trim(comboGrade.Text) & "'" Set mrc = ExecuteSQL(txtSQL, MsgText) txtSQL = "select * from gradecourse_Info where grade='" & Trim(comboGrade.Text) & "'" Set mrc = ExecuteSQL(txtSQL, MsgText) For i = 0 To listSelectCourse.ListCount - 1 mrc.AddNew mrc.Fields(0) = comboGrade.Text mrc.Fields(1) = listSelectCourse.List(i - 1) mrc.Update Next i End Sub
'自定义过程,删除重复的科目 Private Sub shanchu() For a = 0 To listSelectCourse.ListCount - 1 Step 1 For b = a + 1 To listSelectCourse.ListCount - 1 Step 1 If listSelectCourse.List(a) = listSelectCourse.List(b) Then listSelectCourse.RemoveItem b End If Next b Next a End Sub '同样是删除重复的科目,这次是删除左侧listbox框里的数据 Private Sub shanchuleft() For m = 0 To listAllcourse.ListCount - 1 Step 1 For n = m + 1 To listAllcourse.ListCount - 1 Step 1 If listAllcourse.List(m) = listAllcourse.List(n) Then listAllcourse.RemoveItem n End If Next n Next m End Sub
Private Sub cmdAdd_Click() '单选按钮的单击事件 If listAllcourse.ListIndex <> -1 Then listSelectCourse.AddItem listAllcourse.List(listAllcourse.ListIndex) End If Call shanchu End Sub Private Sub cmdDelete_Click() If listSelectCourse.ListIndex <> -1 Then listSelectCourse.RemoveItem listSelectCourse.ListIndex End If Call shanchuleft End Sub