ListBox and Delegate question

M

Mika M

My application receives data from serial port attached equipment. When
data is received then it is saved into database, and shows event log in
ListBox-control like...

Delegate Sub SetTextCallback(ByVal [text] As String)

Private Sub LogEvent(ByVal [msg] As String)
If (Me.lstEventLog.InvokeRequired) Then
Dim d As New SetTextCallback(AddressOf LogEvent)
Me.Invoke(d, New Object() {[msg]})
Else
lstEventLog.Items.Add(String.Format("{0} : {1}", Now, msg))
End If
End Sub

....and it's working fine, but how can I set selected index automatically
to the last one in the ListBox without "Cross-thread operation not
valid: Control 'lstEventLog' accessed from a thread other than the
thread it was created on."-errors. I mean something like...

lstEventLog.SelectedIndex = lstEventLog.Items.Count - 1
 
M

Mika M

Oh! Looks it is working simply like this way...

Private Sub LogEvent(ByVal [msg] As String)
If Me.lstEventLog.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf LogEvent)
Me.Invoke(d, New Object() {[msg]})
Else
lstEventLog.Items.Add(String.Format("{0} : {1}", Now, msg))
lstEventLog.SelectedIndex = lstEventLog.Items.Count - 1
End If
End Sub

Didn't get it to work earlier because of little writing error :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top