刷新数据库VB.NET

时间:2014-11-21 13:56:21

标签: database vb.net instant-messaging

所以我有一个与数据库一起使用的即时消息功能。每次发送消息时,它都会将数据库中消息列中的内容打印到我的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

1 个答案:

答案 0 :(得分:0)

我认为您的问题在于此部分:

'-------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