Vb.net 如何在执行SQL命令后立即刷新DataGridView

Vb.net 如何在执行SQL命令后立即刷新DataGridView,vb.net,Vb.net,我试图在执行SQL命令后立即刷新DataGridView,因此当用户按下update按钮时,所有详细信息必须与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

我试图在执行
SQL
命令后立即刷新
DataGridView
,因此当用户按下update按钮时,所有详细信息必须与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

你可以在这里做一件事。保存成功后,调用用于在
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
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
在“查看”选项卡中,几乎没有关于用户希望如何查看考勤记录的选项,这是通过从组合框中选择选项,然后单击
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\u单击(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)
End Sub
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

试试看。:)

将此类用于Microsoft SQL,并查看LoadDB以了解如何使用它。也不要像以前那样硬编码查询。使用你的应用程序的人可以执行SQL注入并删除你的表。像我教你的那样使用params。您可能还希望只更新特定记录,因此在查询中添加WHERE指令

Sub LoadDB
dim xdb as new dbMSSQL
dim SQLQuery as String = "update Addemployees set fname=@colfname, lname=@collanme, etc WEHRE ID=@colID"

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
这里是一个项目的实际代码

   Dim xDB As New mysql
    xDB.AddParam("@colisconnected", 1)
    xDB.AddParam("@colcpuid", CPUid)
    xDB.AddParam("@colfwuid", userId)
    xDB.ExecQuery("UPDATE clients.computerinfo SET isconnected=@colisconnected WHERE (cpuid=@colcpuid) and (customerid=@colfwuid)")

您只需创建一个在DATAGRIDVIEW中显示数据的方法或函数,然后在添加/删除/更新时调用该方法即可。请确保在调用该方法或函数之前先添加/删除/更新

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
只需在保存/删除/更新数据库后立即添加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()

A) 永远不要使用字符串来生成SQL—它冗长、危险、难以读取且容易出错。使用SQL参数,B)这里没有与DGV相关的内容,但是如果使用数据源,您可以轻松地进行实际刷新,这非常有帮助。您应该改名为table employees。并查看整个表SQLQuery=“SELECT*from employess”。SQL Express只能在本地工作,对数据库大小的限制会更好。你需要你的应用程序在网络上工作,考虑使用MySQL。我可以为您提供一个与MSSQL类工作方式相同的类。这太棒了。我真的很感激你的建议,非常感谢。我将尝试代码并回复。@OuallaWalid我一直在使用这个类。我添加了一些功能,比如getrecord(Table,ID),这样我就不必一直重新编写代码行了。谢谢你,我会试试这个,然后回复Glad来帮助你。我已经试过了,这真的很有帮助,非常感谢。没问题,别忘了投票,如果答案对你有帮助的话