Search code examples
databasevb.netinstant-messaging

Refreshing Database VB.NET


So I have instant messaging functionality that I use with a database. Each time a message is sent it prints what's in the message column in the database into a rich text box in my vb.net application

My problem is. I have to click on the "send message" button twice to get the functionality to work, as the first time I click it, nothing happens

Does anyone have any idea where I'm gone wrong? Much appreciated!

 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

Solution

  • I think your problem is this section:

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

    Why are you skipping a line? This will cause every other message in the table to not be written out, and therefore that's why you have to press it twice so that it shows up. You don't need to manually increment the indexer in a For loop, I suggest you try this:

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