2017-08-28 72 views
-1

我試圖在執行SQL命令後立即刷新DataGridView,因此當用戶按下更新按鈕時,所有細節都必須和DataGridView一樣更改。這是我的代碼,我不知道在哪裏添加此功能。如何在執行SQL命令後立即刷新DataGridView

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click, Button5.Click 
    Try 
     Dim a As String 

     cn.Open() 

     Dim cmd As New System.Data.SqlClient.SqlCommand 
     cmd = New SqlCommand("update Addemployees set Fname= '" & TextBox1.Text & "', Lname= '" & TextBox3.Text & "', ID= '" & TextBox4.Text & "', CIN= '" & TextBox2.Text & "', phone= '" & TextBox6.Text & "', Email= '" & TextBox5.Text & "', fromD= '" & TextBox8.Text & "', toD= '" & TextBox7.Text & "' where ID='" & ComboBox1.Text & "' ", cn) 

     cmd.Connection = cn 
     a = cmd.ExecuteNonQuery() 
     MessageBox.Show("Process successful!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information) 

     cn.Close() 

    Catch 
     MessageBox.Show("Error!", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error) 
    Finally 
     cn.Dispose() 
    End Try 
    TextBox1.Clear() 
    TextBox2.Clear() 
    TextBox3.Clear() 
    TextBox4.Clear() 
    TextBox5.Clear() 
    TextBox6.Clear() 
    TextBox7.Clear() 
    TextBox8.Clear() 
    DateTimePicker2 = Nothing 
    DateTimePicker1 = Nothing 


End Sub 
+2

A)永遠不要concat字符串來製作SQL - 它很單調,很危險,很難閱讀和容易出錯。使用SQL參數,B)沒有任何與DGV相關的內容,但是如果您使用數據源,則可以輕鬆地進行實際刷新 – Plutonix

+0

非常感謝您的確認識,這真的很有幫助。 –

回答

1

您只需創建一個方法或顯示數據的功能添加WHERE指令查詢

Sub LoadDB 
dim xdb as new dbMSSQL 
dim SQLQuery as String = "update Addemployees set [email protected], [email protected], etc WEHRE [email protected]" 

xdb.addparam("@colid",RecordID) 
xdb.addparam("@colfname",textbox1.text) 
xdb.addparam("@collname",textbox2.text) 
....... 

xdb.execquery(Sqlquery) 
datagridview1.datasource=xdb.dbdt 
end sub 



    Imports System.Data.SqlClient 



    Public Class dbMSSQL 
     ' CREATE YOUR DB CONNECTION 
     Public SQLSource As String = "Data Source=[yourcomputer]\sqlexpress;Integrated Security=True" 




     Private DBCon As New SqlConnection(SQLSource) 
     'Private DBCon As New MySqlConnection(SQLSource) 

     ' PREPARE DB COMMAND 
     Private DBCmd As SqlCommand 

     ' DB DATA 
     Public DBDA As SqlDataAdapter 
     Public DBDT As DataTable 

     ' QUERY PARAMETERS 
     Public Params As New List(Of SqlParameter) 

     ' QUERY STATISTICS 
     Public RecordCount As Integer 
     Public Exception As String 

     Public Sub ExecQuery(Query As String) 
      ' RESET QUERY STATS 
      RecordCount = 0 
      Exception = "" 


      Try 
       ' OPEN A CONNECTION 
       DBCon.Open() 

       ' CREATE DB COMMAND 
       DBCmd = New SqlCommand(Query, DBCon) 

       ' LOAD PARAMS INTO DB COMMAND 
       Params.ForEach(Sub(p) DBCmd.Parameters.Add(p)) 

       ' CLEAR PARAMS LIST 
       Params.Clear() 

       ' EXECUTE COMMAND & FILL DATATABLE 

       DBDT = New DataTable 
       DBDA = New SqlDataAdapter(DBCmd) 
       RecordCount = DBDA.Fill(DBDT) 
      Catch ex As Exception 
       Exception = ex.Message 
      End Try 


      ' CLOSE YOUR CONNECTION 
      If DBCon.State = ConnectionState.Open Then DBCon.Close() 
     End Sub 

     ' INCLUDE QUERY & COMMAND PARAMETERS 
     Public Sub AddParam(Name As String, Value As Object) 
      Dim NewParam As New SqlParameter(Name, Value) 
      Params.Add(NewParam) 
     End Sub 

    End Class 

這裏實際代碼首先調用的方法或函數

Sub display() 
    Dim temp As Double = 0 
    Dim lt As String = "select id as ID, vlname as Last, vfname as First, 
       vmname as Middle, vgnd as Gender, vdob as Birthday, iage as 
       Age, vcourse as Course from tbreg where vlname Like '" + 
       tbsearch.Text + "%' or vfname Like '" + tbsearch.Text + "%' 
       order by vlname asc" 
    Dim da As New MySqlDataAdapter(lt, con) 
    con.Open() 

    Dim ds As New DataSet 
    da.Fill(ds, "tbreg") 
    da.Dispose() 
    dgv.DataSource = ds.Tables(0) 
    con.Close() 
End Sub 

物權法之前在DataGridView,然後調用,只要你的方法添加/刪除/更新只是一定要添加/刪除/更新T /加display()方法保存/刪除之後更新數據庫

「更新,然後刷新DataGridView中做更新你 之後只需要調用該方法

Dim supdate As String = "Update tbuser set vname = '" & tbname.Text & "', 
        vemail = '" & tbemail.Text & "', vuser = '" & 
        tbuser.Text & "', vpass = '" & tbpass.Text & "' where 
         vid = '" & dgv.SelectedCells(0).Value & "'" 

Dim cmd As New MySqlCommand(supdate, con) 
con.Open() 
cmd.ExecuteNonQuery() 
MsgBox("Successfully Updated!!!", MsgBoxStyle.Information, 
         "System COnfirmed!") 
con.Close() 
'display method here! 
display() 
+0

謝謝,我會嘗試這個,並回復 –

+0

它工作非常感謝你。 –

+0

很高興能有所幫助 – HazzoN

0

你可以在這裏做一件事。保存成功後,調用您用來查看DataGridView中的內容的步驟。

我會告訴你我的例子:

我有一個學生出勤率添加/觀看形態。有一個TabControl有兩個選項卡,一個用於添加,另一個用於查看。

在添加選項卡中,有一個按鈕將學生的出勤提交給數據庫。提交完成後,我則顯示如下消息:

Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click 
'{rest of the code} 
'add attendance success 
    MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information) 
End Sub 

在視圖選項卡中,有關於用戶如何希望看到這是由從ComboBoxes,然後選擇選項來完成考勤記錄幾個選項點擊SearchBtn按鈕。

'search attendance 
Private Sub SearchBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchBtn.Click 
    If SelectClass2.Text = "" Or SearchType.Text = "" Or SearchKey.Text = "" Then 
     MsgBox("Select search options to continue", MsgBoxStyle.Critical) 
    Else 
     If SearchType.Text = "By Date" Then 
      'search by date, call procedure 'displayatt' 
      Dim xyz As String = SearchKey.Text.Substring(0, 5) 
      displayatt(SearchKey.Text, SelectClass2.Text, String.Format("YYYY/MM/DD", xyz), True) 
     Else 
      'search by student, call procedure 'displayatt' 
      displayatt(SearchKey.Text.Substring(3, SearchType.Text.Length - 3), SelectClass2.Text, SearchKey.Text.Substring(0, 5), False) 
     End If 
    End If 
End Sub 

好了,你可以通過調用其顯示內容的程序更新DataGridView1內容。在我的情況下,我會添加SearchBtn_Click(SearchBtn, Nothing)顯示有關完成添加考勤的信息框。然後它會看起來像這樣:

Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click 
'{rest of the code} 
'add attendance success 
    MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information) 
    SearchBtn_Click(SearchBtn, Nothing) 
End Sub 

試試吧。 :)

+0

我已經嘗試過,這非常有用非常感謝你。 –

+0

沒問題,不要忘記投票的答案,如果它幫助你 – Subaz

0

將此類用於Microsoft SQL,並參閱LoadDB以瞭解如何使用它。也不要像你那樣硬編碼你的查詢。有人使用您的應用程序可以執行SQL注入並刪除您的表。使用像我向你展示的參數。你可能也想更新只特定的記錄,因此從項目

Dim xDB As New mysql 
    xDB.AddParam("@colisconnected", 1) 
    xDB.AddParam("@colcpuid", CPUid) 
    xDB.AddParam("@colfwuid", userId) 
    xDB.ExecQuery("UPDATE clients.computerinfo SET [email protected] WHERE ([email protected]) and ([email protected])") 
+0

你應該命名你的員工代替。並查看您的整個表SQLQuery =「選擇*從employess」。 SQL Express只能在本地工作,並且對數據庫大小的限制會更好。考慮使用mysql,你需要你的應用程序通過網絡工作。我可以爲您提供一個與MSSQL類相同的類。 – 2017-08-28 17:40:54

+0

這真是太棒了。我非常感謝你的建議,非常感謝你。我會嘗試代碼並回復。 –

+0

@OuallaWalid我一直都在使用這個類。我爲getrecord(Table,ID)添加了一些功能,所以我不必一直重寫代碼行。 – 2017-08-30 04:18:44