2014-11-21 77 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