Database 刷新数据库VB.NET

Database 刷新数据库VB.NET,database,vb.net,instant-messaging,Database,Vb.net,Instant Messaging,因此,我有即时消息功能,我使用的数据库。每次发送消息时,它都会将数据库中消息列中的内容打印到我的vb.net应用程序的富文本框中 我的问题是。我必须点击发送消息按钮两次才能让功能正常工作,因为第一次点击时,什么也没发生 有人知道我哪里出错了吗?非常感谢 Try '----------------Sends the message------------------------------------- MysqlConn.Open() ' opening the

因此,我有即时消息功能,我使用的数据库。每次发送消息时,它都会将数据库中消息列中的内容打印到我的vb.net应用程序的富文本框中

我的问题是。我必须点击发送消息按钮两次才能让功能正常工作,因为第一次点击时,什么也没发生

有人知道我哪里出错了吗?非常感谢

 Try
        '----------------Sends the message-------------------------------------
        MysqlConn.Open() ' opening the connection to the DB
        Dim query As String
        query = "insert into dojodb.chats (Message) values ('" & txtMessage.Text & "')"
        command = New MySqlCommand(query, MysqlConn)
        reader = command.ExecuteReader 'executes the command and reads data from db
        reader.Close()


        '-------------------Retreives the message------------------------------------
        Dim sqlStr As String = "SELECT * FROM chats"
        Dim chatcommand As New MySqlCommand(sqlStr, MysqlConn)
        Dim rdr As MySqlDataReader = chatcommand.ExecuteReader()
        Dim tbl As New DataTable
        tbl.Load(rdr)


        '-------For every row, print the message, skip a line, and add 1 so it goes to next msg--------
        For i As Integer = 0 To tbl.Rows.Count - 1
            rowIndex = i
            strOutPut &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
            i = i + 1
        Next

        txtGroupChat.Text = strOutPut
        strOutPut = "" 'clearing the string so that it does not print out duplicate info next time

        '-------------------------End Retrieve-------------------------------------------

        MysqlConn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message) 'printing the exact error to help future testing if needed
    Finally
        MysqlConn.Dispose()
    End Try
End Sub

我认为你的问题在于这一部分:

'-------For every row, print the message, skip a line, and add 1 so it goes to next msg--------
For i As Integer = 0 To tbl.Rows.Count - 1
    rowIndex = i
    strOutPut &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
    i = i + 1
Next
你为什么跳过一行?这将导致表中的所有其他消息都无法写出,因此必须按两次才能显示。您不需要在For循环中手动递增索引器,我建议您尝试以下方法:

For i As Integer = 0 To tbl.Rows.Count - 1
    rowIndex = i
    strOutPut &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
Next

这不是你问题的答案,但如果你不知道,你可能还想仔细阅读一下,我有一个名为pk的字段,每次消息保存到数据库时,它都会自动递增。这是主键,用于按要打印到文本的最早最新消息对消息进行排序box@JamesThorpe,我的数据库是安全的。我没有透露任何敏感的连接信息。SQL注入不需要连接信息。假设有人在聊天消息中键入消息oops'go drop table dojodb.chats go。我建议你在尝试之前先考虑一下……哈哈,真的,从来没有这样想过,谢谢你!