Wednesday, August 8, 2012

Safe thread in a listview. Getting the CheckListViewCollection

I am working with an application in .NET Framework 2.0. I am trying to work with a Safe-Thread method that will help me to get the checkitems in a listview. This is a reminder to my self. I had seen a lot of examples with textboxes, but few with listviews.

 First we need to create a delegate.
'Delegate for getting the CheckListItems
Private Delegate Function GetCheckListItems(lst As ListView) As ListView.CheckedListViewItemCollection

'this maybe in a button
Dim t As New Threading.Thread(AddressOf yourMethod)   
t.start
Private Sub YourMethod()    
'Something TODO....    
Dim x As String = GetValuesFromList()
end
Private Function GetValuesFromList() As String    
'there is not validation of any kind on this.    
'the purpose is just to use a safe-thread with a
' listview.CheckedListViewCollection
Dim mylist As New StringBuilder    
Dim lst As ListView.CheckedListViewItemCollection = getListViewItems(MyListView)    
For Each item As ListViewItem In lst
  mylist.Append(item.Tag.ToString & ",")    
Next    
Return mylist.ToString
End

'This is the safe call. We need to copy the items from one listview to another
' that way we avoided the cross-thead
' It is important set Checkboxes property to true. Without that the selected check items
' will not be copied to the temp variable.
Function Private Function getListViewItems(lstview As ListView) As ListView.CheckedListViewItemCollection    
 Dim temp As New ListView    
 temp.CheckBoxes = True    
If Not lstview.InvokeRequired Then        
 For Each item As ListViewItem In lstview.Items            
     temp.Items.Add(DirectCast(item.Clone(), ListViewItem))        
  Next        
  Return CType(temp.CheckedItems, ListView.CheckedListViewItemCollection)    
Else        
 Return DirectCast(Me.Invoke(
   New GetCheckListItems(AddressOf getListViewItems), New Object() {lstview}),  
   ListView.CheckedListViewItemCollection)    
End If
End Function

No comments:

Post a Comment