2014-11-21 99 views
0

因此,我具有即時消息功能,我使用數據庫。每發送一條消息,它都會將數據庫中的消息列中的內容打印到我的vb.net應用程序中的一個富文本框中。刷新數據庫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 
+0

不回答你的問題,但如果你沒有意識到這一點,你可能需要閱讀[SQL注入](http://en.wikipedia.org/wiki/SQL_injection) – 2014-11-21 13:59:05

+0

此外,我有一個名爲「pk」的字段,每次將消息保存到數據庫時自動遞增。這是主鍵,用於按最老的順序對郵件進行分類 - 最新打印到文本框 – foley 2014-11-21 14:00:40

+0

@JamesThorpe,我的數據庫很安全。我沒有透露任何敏感的連接信息 – foley 2014-11-21 14:01:46

回答

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