Prevent ListView Row Disappearing Upon Data Update - vb.net

I have a listview that displays message items. When the parent window is open, it starts a timer that checks every xx amount to see if any new messages have been sent. This then clears the listview control and rebuilds it everytime (not sure if this is the best way).
Anyway, if the mouse is sitting over the top of a listview item when the listview gets rebuilt, the listview row is blank. However, moving the mouse off the item and back on the item will redraw it fine.
The code to build my listview is such:
Private Sub LoadMessages()
Dim QueryString As String
Try
lsvMail.Items.Clear()
QueryString = "SELECT * FROM Mail WHERE recipient = '" & Current_User.DisplayName & "' ORDER BY sent DESC"
Dim ExQry As New MySqlCommand(QueryString, MySQLConn)
Dim da As New MySqlDataAdapter(ExQry)
da.Fill(dsMessages, "Messages")
Dim tempDT As DataTable = dsMessages.Tables("Messages")
If dsMessages.Tables.Count > 0 And dsMessages.Tables(0).Rows.Count > 0 Then
For x = 0 To (dsMessages.Tables(0).Rows.Count - 1)
Dim lvi As New ListViewItem(tempDT.Rows(x)("is_replied").ToString)
lvi.SubItems.Add(tempDT.Rows(x)("sender").ToString)
If CBool(tempDT.Rows(x)("is_read")) = True Then
lvi.Font = RegularFont
Else
lvi.Font = BoldFont
End If
If CBool(tempDT.Rows(x)("is_followup")) = True Then
lvi.ForeColor = Color.Red
Else
lvi.ForeColor = Color.Black
End If
lvi.SubItems.Add(tempDT.Rows(x)("subject").ToString)
lvi.SubItems.Add(tempDT.Rows(x)("sent").ToString)
lvi.SubItems.Add(tempDT.Rows(x)("is_followup").ToString)
lvi.Name = tempDT.Rows(x)("id").ToString
lsvMail.Items.Add(lvi)
Next
End If
da = Nothing
tempDT = Nothing
dsMessages.Clear()
Catch ex As Exception
CreateLog("Module: LoadMailMessages()" & vbNewLine & "Exception Error: " & ex.Message)
MsgBox("Exception Error: " & ex.Message, MsgBoxStyle.Critical, "Module: LoadMailMessages()")
End Try
End Sub
Like mentioned, I have a timer event that simply calls the LoadMessages() routine.
I am trying to have a 'live' feed to the messages window so that new items will appear in the listview if the window is open.
Any help appreciated - thanks.

Try adding refresh:
Next
lvi.Refresh()
End If

Related

VB How to Clear existing items in listview

I am trying to search the information from the sql server then show at the listview. Everytime I click search it won't clear the existing records based on the past time searching. I've tried item.clear, it will only show me the new search but it won't clear all the existing records. Can someone help please?
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim strNameSource As String
Dim strPhoneSource As String
Dim strBothSource As String
If OpenConnect() = True Then
Try
If ChkCustName.Checked = True Then
strNameSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strNameSource)
ElseIf ChkPhoneNumber.Checked = True Then
strPhoneSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "'"
SearchReservation(strPhoneSource)
ElseIf ChkCustName.Checked = True And ChkPhoneNumber.Checked = True Then
strBothSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "' AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strBothSource)
End If
txtLastName.Clear()
txtPhoneNumber.Clear()
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End If
End Sub
Private Sub SearchReservation(ByVal strSource As String)
Dim itemcollection(100) As String
Dim Row As Integer
Dim Column As Integer
Dim ListViewItem As New ListViewItem
lstReservation.Items.Clear()
Try
cmd = New OleDb.OleDbCommand(strSource, cnn)
Adapter = New OleDb.OleDbDataAdapter(cmd)
Adapter.Fill(Ds, "Table")
'Now adding the Items in Listview
If Ds.Tables(0).Rows.Count = 0 Then
' Something went wrong. warn user
MessageBox.Show(Me, "Could not find the Customer", "Customer finding Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
lstReservation.BeginUpdate()
For Row = 0 To Ds.Tables(0).Rows.Count - 1
For Column = 0 To Ds.Tables(0).Columns.Count - 1
itemcollection(Column) = Ds.Tables(0).Rows(Row)(Column).ToString()
Next
ListViewItem = New ListViewItem(itemcollection)
lstReservation.Items.Add(ListViewItem)
Next
lstReservation.EndUpdate()
End If
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End Sub
Lots of issues with your code, but I'll focus on your immediate issue.
You keep filling the DataSet with new tables, but you keep using the original table that is still in position zero of the DataSet.
I would venture a guess that you need to clear the rows of your DataTable:
If Ds.Tables.Contains("Table") Then
Ds.Tables("Table").Rows.Clear()
End If
lstReservation.Items.Clear()
of just clear any tables there:
Ds.Tables.Clear()
lstReservation.Items.Clear()

connecting datatable with datagrid asp.net

so i was trying to bind my datagrid to a datatable and i came up with this code
now everything seems to be working but it does not shows nothing on my gridview it doesnt even shows the datagrid at all when i execute anyone know what is the problem because i cant figure it out everything should be working fine but the gridview does not load .
Dim mrDB As New Odbc.OdbcConnection(myDAC.OBDC)
Dim dgrMR As New DataTable
Dim dr As DataRow
dgrMR.Columns.Add("Data")
dgrMR.Columns.Add("Utente")
dgrMR.Columns.Add("Nome")
dgrMR.Columns.Add("Série")
dgrMR.Columns.Add("Tipo")
dgrMR.Columns.Add("Estado")
dgvMarcacoes.Columns.Clear()
Dim sqlStr As String = "select distinct data,idno,idnome, u_tratam as serie, u_tipomr, Max(estado) as estado " &
"from [marca].[mr]"
sqlStr += queryFilter
sqlStr += "group by idno,idnome, u_tratam, data, u_tipomr "
'this msgbox shows a correct string (that works on sql) so the problem is not on this part
'MsgBox(sqlStr, MsgBoxStyle.OkOnly, "controlo")
mrDB.Open()
Dim mrComm As New Odbc.OdbcCommand(sqlStr, mrDB)
Dim mrReader = mrComm.ExecuteReader
Dim b = New StringBuilder()
If Not (mrReader.HasRows) Then
Me.dgvMarcacoes.Visible = False
MsgBox("Não há marcações para o dia indicado", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "ATENÇÃO...")
Else
'Me.dgvMarcacoes.Visible = True
While mrReader.Read
dr = dgrMR.NewRow()
dr(0) = Trim(mrReader(0))
dr(1) = Trim(mrReader(1))
dr(2) = Trim(mrReader(2))
dr(3) = Trim(mrReader(3))
dr(4) = Trim(mrReader(4))
dr(5) = Trim(mrReader(5))
dgrMR.Rows.Add(dr)
'dr.Item(5).Value = Trim(estado(mrReader(5)))
End While
End If
dgvMarcacoes.DataSource = dgrMR
dgvMarcacoes.DataBind()
mrDB.Close()
'so i tried this to see if the data was passing correctly to my datatable and it is :\
For i = 0 To dgrMR.Rows.Count - 1
For u = 0 To dgrMR.Columns.Count - 1
MsgBox(dgrMR.Rows(i)(u).ToString)
Next
Next
You have a tag as asp.net but you have MsgBox in your code indicating that is a WinForm application. Check if the grid columns are AutogenerateColumns=True and change it to false

Background Worker Not Clearing Resources

I'm currently working on an application that fetches some information from a database using a BW. It uses a stores number, referred to as IDP and searches the correct database. It works perfectly for my needs. However, each time it runs it's adding anywhere between 10-300 KBs to RAM, it is not releasing this memory once it completes. Since this code can be ran hundreds of times a day by numerous different people on a virtual machine with limited resources I really need it to release any memory it uses. Can anyone see where I'm going wrong?
Note: I'm self-taught and I'm doing this as more of a hobby that helps me out at work and not actually employed to do this, as I'm sure some of you will be happy to know once seeing my newbie code.
Public Sub KickoffStoreBrief() 'Called when txtIDP (text box) text changes
Dim args As BW_GetStoreBriefVariables = New BW_GetStoreBriefVariables()
args.Current_IDP = txtIDP.Text.Trim
If BW_GetStoreBrief.IsBusy Then
MsgBox("Worker busy!")
Else
BW_GetStoreBrief.RunWorkerAsync(args)
End If
End Sub
Private Sub BW_GetStoreBrief_DoWork(sender As Object, e As DoWorkEventArgs) Handles BW_GetStoreBrief.DoWork
Dim args As BW_GetStoreBriefVariables = DirectCast(e.Argument, BW_GetStoreBriefVariables) 'Convert the generic Object back into a MyParameters object
Using DatabaseConnection As New SqlConnection(args.ConnectionString)
Dim command As New SqlCommand(SQL CODE IS HERE, DatabaseConnection)
command.CommandTimeout = 20
'Attempt to open the connection
command.Connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
Dim dt As New DataTable()
dt.Load(reader)
reader = Nothing
'Check if returned anything
If dt.Rows.Item(0).Item(0) = Nothing Or dt.Rows.Item(0).Item(0).ToString = "False" Or dt.Rows.Item(0).Item(0).ToString = "" Then
'Branch not found.
GoTo Ender
End If
'Prefix 0's infront of the IDP as required
Dim CompleteIDPNumber As String = ""
If dt.Rows.Item(0).Item(0).ToString.Length < 4 Then
If dt.Rows.Item(0).Item(0).ToString.Length = 2 Then
CompleteIDPNumber = "00" & dt.Rows.Item(0).Item(0).ToString
ElseIf dt.Rows.Item(0).Item(0).ToString.Length = 3 Then
CompleteIDPNumber = "0" & dt.Rows.Item(0).Item(0).ToString
Else
CompleteIDPNumber = dt.Rows.Item(0).Item(0).ToString
End If
Else
CompleteIDPNumber = dt.Rows.Item(0).Item(0).ToString
End If
'Populate strings
Dim StoreName As String = CompleteIDPNumber & " - " & dt.Rows.Item(0).Item(1).ToString.Trim
Dim UISupports As Integer = 20 'This is the amount of characters that will fit in label space
If StoreName.Length > UISupports Then
StoreName = StoreName.Substring(0, UISupports).ToString.Trim & "..." & " (" & dt.Rows.Item(0).Item(3).ToString.Trim & ")"
Else
StoreName = StoreName & " (" & dt.Rows.Item(0).Item(3).ToString.Trim & ")"
End If
args.Brief_StoreName = StoreName
StoreName = Nothing 'We no longer need this, release it from memory
UISupports = Nothing 'We no longer need this, release it from memory
CompleteIDPNumber = Nothing 'We no longer need this, release it from memory
If dt.Rows.Item(0).Item(2) = 0 Or dt.Rows.Item(0).Item(2).ToString.Trim = "0" Then
args.Brief_POSNumber = "IS"
Else
args.Brief_POSNumber = dt.Rows.Item(0).Item(2).ToString.Trim
End If
args.Brief_Category = dt.Rows.Item(0).Item(3).ToString 'CAT
args.Brief_STCamera = dt.Rows.Item(0).Item(4).ToString 'Counter
args.Brief_Franch = dt.Rows.Item(0).Item(5).ToString
Ender:
e.Result = args
'Close connection
dt.Dispose()
command.Connection.Close()
command.Dispose()
End Using
End Sub
Private Sub BW_GetStoreBrief_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BW_GetStoreBrief.RunWorkerCompleted
If e.Error IsNot Nothing Then
ListBox1.Items.Insert(0, Now.ToString("HH:mm:ss") & " | Error | Unable to connect to store DB.")
lblNotFound.Text = "Unable to connect to database."
Panel_NotFound.Visible = True
Panel_NotFound.BringToFront()
ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Error.Message, 0)
ElseIf e.Cancelled Then
Else
' Access variables through args
Dim args As BW_GetStoreBriefVariables = DirectCast(e.Result, BW_GetStoreBriefVariables) 'Convert the generic Object back into a MyParameters object
If args.Brief_StoreName = "" Then
ListBox1.Items.Insert(0, Now.ToString("hh:mm:ss") & " | Notice | IDP " & args.Current_IDP & " not found in database.")
'show warning panel
lblNotFound.Text = "Store not found in database."
Panel_NotFound.Visible = True
Panel_NotFound.BringToFront()
GoTo Ender
Else
'Store found update UI
lblBranchInfo_StoreName.Text = args.Brief_StoreName
lblBranchInfo_POSNumber.Text = args.Brief_POSNumber
lblBranchInfo_CameraType.Text = args.Brief_STCamera
Panel_NotFound.Visible = False
Panel_NotFound.SendToBack()
End If
args = Nothing
End If
Ender:
btnStoreDetails.Enabled = True
End Sub
As you can see i've tried to make sure I'm not leaving anything behind, but the memory keeps jumping up and doesn't go down. Overall we're talking about 35MBs being used when this codes been ran only a few times and nothing else is happening with the program/form. Because this is on a remote virtual machine the program can be open for days without being closed, and with the memory usage increasing each time it will become a very big issue. Any help would be appreciated.

Error when I set a radio button to be checked by default

I have a radio button in my VB.NET dll that I wan't to be checked by default. There is a total of 3 radio buttons in this group. Under its properties I set Checked = true. I verified the code was there, this is all the form generated code for the radio button:
Me.rdbProductPC.AutoSize = True
Me.rdbProductPC.Checked = True
Me.rdbProductPC.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.rdbProductPC.Location = New System.Drawing.Point(49, 12)
Me.rdbProductPC.Name = "rdbProductPC"
Me.rdbProductPC.Size = New System.Drawing.Size(45, 17)
Me.rdbProductPC.TabIndex = 1
Me.rdbProductPC.TabStop = True
Me.rdbProductPC.Text = "P&&C"
Me.rdbProductPC.UseVisualStyleBackColor = True
For some reason I get this error when I start the application:
An error occurred creating the form. See Exception.InnerException for details. The error is: ExecuteReader requires an open and available Connection. The connection's current state is closed.
Nothing has changed besides the one line adjusting the checked value. Any idea what could be causing this?
This is the code for my GetProducts() method. The error arises after the call to ExecuteReader() but I cannot see the code for this. If my g_strSQL = pc_mis_busunit_product_relate_summary it executes fine. But when g_strSQL = pc_mis_busunit_product_relate_summary '','','N' it errors out.
That being said, if I leave the radio button unchecked by default and then check it later while the program is running it will go into this same method and g_strSQL will look like pc_mis_busunit_product_relate_summary '','','N' and it will work fine.
Private Sub GetProducts(ByVal ProductList As ListBox)
Dim g_strSQL As String
ProductList.Items.Clear()
lstProductSel.Items.Clear()
lstProduct.Enabled = True
g_strSQL = String.Empty
objcmd.Connection = ControlConnection
'Clear location combo box
Select Case intProduct
Case Product.Summary
g_strSQL = g_strSQL & "pc_mis_busunit_product_relate_summary "
Case Product.Detail
g_strSQL = "SELECT DISTINCT b.dtl_prod_cd, rtrim(ltrim(b.dtl_prod_desc))"
g_strSQL = g_strSQL & " FROM product_detail_ref b "
g_strSQL = g_strSQL & " ORDER BY rtrim(ltrim(b.dtl_prod_desc)) "
Case Else
Exit Sub
End Select
If p_and_C <> String.Empty Then
g_strSQL = g_strSQL & "'" & String.Empty & "','" & String.Empty & "','" & p_and_C & "'"
End If
If g_strSQL <> "" Then
objcmd.CommandText = g_strSQL
rsProducts = objcmd.ExecuteReader()
End If
'Process results from query
If rsProducts.HasRows = False Then
rsProducts.Close()
Exit Sub
Else
' This nested if will check which radio button is selected and add the corresponding
' 'all' entry to the top of the lstProduct box
If rdbProductPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_P_AND_C)
ElseIf rdbProductNonPC.Checked = True Then
ProductList.Items.Add(PAndCConstants.ALL_NON_P_AND_C)
Else
ProductList.Items.Add(PAndCConstants.ALL)
End If
ProductList.SelectedIndex = 0
While rsProducts.Read()
ProductList.Items.Add(rsProducts(0))
End While
ProductList.SetSelected(0, True)
rsProducts.Close()
End If
rsProducts = Nothing
End Sub

How to use timer in vb.net

I have this code:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim num As String
Dim message As String
Dim name As String
message = txtMessage.Text
Dim count As Integer = Me.TblContactsBindingSource.Count
If i < TblContactsDataGridView.Rows.Count - 1 Then 'stay within bounds
i = i + 1 ' for all rows except Row0
TblContactsDataGridView.Rows(i - 1).DefaultCellStyle.BackColor = Color.White ' restore previous highlight
TblContactsDataGridView.Rows(i).DefaultCellStyle.BackColor = Color.Bisque 'new highlight
num = Me.TblContactsDataGridView.Rows(i).Cells(1).Value.ToString()
name = Me.TblContactsDataGridView.Rows(i).Cells(0).Value.ToString()
If SerialPort1.IsOpen() Then
SerialPort1.Write("AT" & vbCrLf)
SerialPort1.Write("AT+CMGF=1" & vbCrLf)
SerialPort1.Write("AT+CMGS=" & Chr(34) & num & Chr(34) & vbCrLf)
SerialPort1.Write(message & Chr(26))
MessageBox.Show("Message has been successfully sent to " & vbNewLine & name & " (" & num & ") ", "Message Sent", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Else 'next row is off the bottom so
'i = 0 'reset index
'TblSmsDataGridView.Rows(TblSmsDataGridView.Rows.Count - 1).DefaultCellStyle.BackColor = Color.White 'restore bottom row
'TblSmsDataGridView.Rows(i).DefaultCellStyle.BackColor = Color.Bisque 'highlight top row
End If
In a command button I have this:
Timer1.Interval = 2000
Timer1.Enabled = True 'no need to enable it and start it; one or t'other
What happen is, the message box appears over and over. How can i trigger message box to automatically close once it is finished? I commented the code in the "else" because the it repeats over and over.
You have to use a custom message box. Normal message box wont do the thing you wanted. It will pop up every 2 second. best choice is to make a new form and show it as a message box. :)
You need to set timer1.enabled = false in the timer1.tick handler.