機房收費係統之DataGridView
在我們平時的學習中不少見用到將數據庫與界麵連接的一個控件——DataGridView,在我們敲第一遍機房的時候我們用到的相似的控件是——MSHFlexGrid,隨著學習的深入,發現我們用到的平台越來越人性化了,現在用的VS2013的控件——DataGridView可以直接和數據庫相連接,今天重點說一下DataGridView刪除行並同時更新數據庫功能的實現:
這是刪除前的效果,我們要實現的是如圖的效果,左圖為界麵,右圖為數據庫中的數據,但是還需要考慮要刪除的用戶是否正在登錄,如果正在登錄,則不能刪除。
刪除後的效果:
實現這個功能主要是在U層加了一個方法,B層、D層和其他刪除時是大相徑庭的,下麵看一下代碼實現部分:
1、D層:
Public Function DelUser(enUser As UserInfoEntity) As Integer Implements IUserInfo.DelUser Dim cmdText As String Dim sqlParams As SqlParameter() Dim sqlHelper As New SqlHelper Dim intResult As Integer cmdText = "Delete from T_UserInfo where UserID=@UserID" sqlParams = {New SqlParameter("@UserID", enUser.UserID)} intResult = sqlHelper.ExecuteAddDelUpdate(cmdText, CommandType.Text, sqlParams) Return intResult End Function2、B層:
Public Function DelUser(ByVal enUser As UserInfoEntity) As Integer Dim iUserInfo As IUserInfo Dim intResult As Integer iUserInfo = factory.CreateSelectUser() intResult = iUserInfo.DelUser(enUser) Return intResult End Function3、U層:
a.定義一個刪除行的過程:
''' <summary> ''' 刪除用戶的自定義過程 ''' </summary> ''' <remarks></remarks> Public Sub DelUser() Dim intRows As Integer = DataGridView1.SelectedRows.Count '判斷選中的行數 Dim intDelRow As Integer Dim enUser As New UserInfoEntity Dim bllAddDelUser As New AddDelUserBLL Dim strUserID As String '獲取選中數據的第一列值 Dim intResult As Integer If intRows > 0 Then '從下往上刪除,防止漏行 For intDelRow = intRows To 1 Step -1 strUserID = DataGridView1.SelectedRows(intDelRow - 1).Cells("UserIDDataGridViewTextBoxColumn").Value.ToString() '如果該用戶正在工作,則不能刪除 If pubshare.strUserName = strUserID.Trim() Then MsgBox("該用戶正在工作,不能刪除", vbOKOnly + vbExclamation, "提示") Exit Sub Else '將要刪除的用戶ID傳給實體 enUser.UserID = strUserID '同時將該實體的信息從數據庫中刪除 intResult = bllAddDelUser.DelUser(enUser) If intResult > 0 Then '將數據庫中所刪除的對應的信息在dataGridview表中也刪除 DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(intDelRow - 1).Index) MsgBox("刪除成功", vbOKOnly + vbExclamation, "提示") Else MsgBox("刪除失敗", vbOKOnly + vbExclamation, "提示") End If End If Next Else DataGridView1.Rows.Clear() End If End Subb.通過點擊刪除按鈕來實現這個過程:
Private Sub btnDel_Click(sender As Object, e As EventArgs) Handles btnDel.Click If DataGridView1.SelectedRows.Count > 0 Then If MessageBox.Show("確定要刪除所選信息嗎?", "提示", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then DelUser() End If Else MessageBox.Show("請選擇要刪除的用戶!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation) Return End If End Sub僅僅是個人的一點想法,希望和大家交流!
最後更新:2017-04-03 12:56:43