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

时间:2017-08-28 15:56:29

标签: vb.net

我尝试在执行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

3 个答案:

答案 0 :(得分:1)

您可以创建一个在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()

答案 1 :(得分: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

试试吧。 :)

答案 2 :(得分:0)

将此类用于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)")