Objectlistview how check checkboxes in bound data in listview for each row

I need help with objectlistview.
each row has 3 check boxes they are in columns 6, 7 , 8
If conditions are met I need the system to  check the checkboxes
some instances non will be checked or 1 , 2 or all 3 could be checked depends what condition was met

the boxes are data bound

not very good with this control
JasonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Lokesh B RDeveloperCommented:
Hi,

Check this sample, it will check the check-boxes based on the values in some column.

<asp:ListView ID="ListView1" runat="server" ItemPlaceholderID="itemPlaceHolder1" OnItemDataBound="ListView1_ItemDataBound">
                <LayoutTemplate>
                    <table cellpadding="4" cellspacing="0" class="auto-style1">
                        <tr>
                            <td>Name</td>
                            <td>IsAdmin</td>
                            <td>IsUser</td>
                            <td>IsGuest</td>
                        </tr>
                        <asp:PlaceHolder ID="itemPlaceHolder1" runat="server"></asp:PlaceHolder>
                    </table>
                </LayoutTemplate>
                <ItemTemplate>
                    <tr>
                        <td>
                            <asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Id") %>'></asp:Literal></td>
                        <td>
                            <asp:CheckBox ID="CheckBox1" runat="server" /></td>
                        <td>
                            <asp:CheckBox ID="CheckBox2" runat="server" /></td>
                        <td>
                            <asp:CheckBox ID="CheckBox3" runat="server" /></td>
                    </tr>
                </ItemTemplate>
            </asp:ListView>

Open in new window


Protected Sub Page_Load(sender As Object, e As EventArgs)
	If Not IsPostBack Then
		Dim dt As New DataTable()
		dt.Columns.Add("Id")

		For i As Integer = 0 To 3
			dt.Rows.Add(i)
		Next

		ListView1.DataSource = dt
		ListView1.DataBind()
	End If
End Sub

Open in new window


Protected Sub ListView1_ItemDataBound(sender As Object, e As ListViewItemEventArgs)
	If e.Item.ItemType = ListViewItemType.DataItem Then
		' Display the e-mail address in italics.
		Dim ltrId As Literal = DirectCast(e.Item.FindControl("Literal1"), Literal)

		Dim checkBox1 As CheckBox = DirectCast(e.Item.FindControl("CheckBox1"), CheckBox)
		Dim checkBox2 As CheckBox = DirectCast(e.Item.FindControl("CheckBox2"), CheckBox)
		Dim checkBox3 As CheckBox = DirectCast(e.Item.FindControl("CheckBox3"), CheckBox)

		' By default all the checkboxes will be UNCHECKED
		'based on some conditions check box will be ticked as below
		If ltrId.Text = "1" Then
			checkBox1.Checked = True
		End If

		If ltrId.Text = "2" Then
			checkBox1.Checked = True

			checkBox2.Checked = True
		End If

		If ltrId.Text = "3" Then
			checkBox1.Checked = True
			checkBox2.Checked = True
			checkBox3.Checked = True
		End If
	End If
End Sub

Open in new window

0
it_saigeDeveloperCommented:
What conditions do you need met?  It really is just a simple matter of checking the conditions when the row objects properties change.  Assuming that you are using mostly the code that we have collaborated on thus far:

I modified the class that controls the data object (in this case RaceInfo):
Public Class RaceInfo
#Region "Check Changed Event Handlers"
	Private ReadOnly _checkChangedEventHandlers As New List(Of CheckChangedEventHandler)
	Public Custom Event CheckChanged As CheckChangedEventHandler
		AddHandler(ByVal value As CheckChangedEventHandler)
			_checkChangedEventHandlers.Add(value)
		End AddHandler

		RemoveHandler(ByVal value As CheckChangedEventHandler)
			_checkChangedEventHandlers.Remove(value)
		End RemoveHandler

		RaiseEvent(ByVal sender As Object, ByVal e As CheckChangedEventArgs)
			For Each handler As CheckChangedEventHandler In _checkChangedEventHandlers
				Try
					handler.Invoke(sender, e)
				Catch ex As Exception
					Debug.WriteLine(String.Format("Exception while invoking event handler: {0}", ex))
				End Try
			Next
		End RaiseEvent
	End Event

	Protected Overridable Sub OnCheckChanged(ByVal sender As Object, ByVal e As CheckChangedEventArgs)
		RaiseEvent CheckChanged(sender, e)
	End Sub
#End Region

#Region "Private Fields"
	Private fCheck1 As Boolean
	Private fCheck2 As Boolean
	Private fCheck3 As Boolean
	Private fMG As String
	Private fMM As String
	Private fNumber As Integer
	Private fPoolPercentage As Decimal
	Private fRM As String
	Private fRunningPercentage As Decimal
	Private fUDiff As String
	Private fWinOdds As Decimal
#End Region

#Region "Public Properties"
	Public Property Number() As Integer
		Get
			Return fNumber
		End Get
		Set(ByVal value As Integer)
			fNumber = value
			UpdateChecks()
		End Set
	End Property

	Public Property WinOdds() As Decimal
		Get
			Return fWinOdds
		End Get
		Set(ByVal value As Decimal)
			fWinOdds = value
			UpdateChecks()
		End Set
	End Property

	Public Property PoolPercentage() As Decimal
		Get
			Return fPoolPercentage
		End Get
		Set(ByVal value As Decimal)
			fPoolPercentage = value
			UpdateChecks()
		End Set
	End Property

	Public Property RunningPercentage() As Decimal
		Get
			Return fRunningPercentage
		End Get
		Set(ByVal value As Decimal)
			fRunningPercentage = value
			UpdateChecks()
		End Set
	End Property

	Public Property MM() As String
		Get
			Return fMM
		End Get
		Set(ByVal value As String)
			fMM = value
			UpdateChecks()
		End Set
	End Property

	Public Property UDiff() As String
		Get
			Return fUDiff
		End Get
		Set(ByVal value As String)
			fUDiff = value
			UpdateChecks()
		End Set
	End Property

	Public Property MG() As String
		Get
			Return fMG
		End Get
		Set(ByVal value As String)
			fMG = value
			UpdateChecks()
		End Set
	End Property

	Public Property RM() As String
		Get
			Return fRM
		End Get
		Set(ByVal value As String)
			fRM = value
			UpdateChecks()
		End Set
	End Property

	Public Property Check1() As Boolean
		Get
			Return fCheck1
		End Get
		Set(ByVal value As Boolean)
			If Not value.Equals(fCheck1) Then
				fCheck1 = value
				RaiseEvent CheckChanged(Me, New CheckChangedEventArgs("Check1", Check1))
			End If
		End Set
	End Property

	Public Property Check2() As Boolean
		Get
			Return fCheck2
		End Get
		Set(ByVal value As Boolean)
			If Not value.Equals(fCheck2) Then
				fCheck2 = value
				RaiseEvent CheckChanged(Me, New CheckChangedEventArgs("Check2", Check2))
			End If
		End Set
	End Property

	Public Property Check3() As Boolean
		Get
			Return fCheck3
		End Get
		Set(ByVal value As Boolean)
			If Not value.Equals(fCheck3) Then
				fCheck3 = value
				RaiseEvent CheckChanged(Me, New CheckChangedEventArgs("Check3", Check3))
			End If
		End Set
	End Property
#End Region

#Region "Private Methods"
	Private Sub UpdateChecks()
		If fWinOdds > 15 Then
			Check3 = True
		End If
	End Sub
#End Region
End Class

Open in new window

So that whenever the field properties change, I can then update the checkboxes by calling the UpdateChecks method.  So putting it all together:
Form1.vb -
Imports BrightIdeasSoftware
Imports System.ComponentModel
Imports System.Reflection

Public Class Form1
	Private Races As SortableBindingList2(Of RaceInfo)
	Private IsSorting As Boolean = False
	Private TypedList As TypedObjectListView(Of RaceInfo)
	Private data As String = "OK Win Approximates 00:00:00" & vbCrLf _
	 & "SG,GOSFORD,4,STEVE BLYTH ELECTRICAL STAKE M,20081104,515,GOOD,OCAST,CLOSED,19:57:39" & vbCrLf _
	 & "3,10, , , ,19:57:00,19:58:11,19:57:22,19:56:37" & vbCrLf _
	 & "1,N,INSTANT GABBIE,PETER JOHNSON,1,0.0,10.30,11.00,7.70" & vbCrLf _
	 & "2,N,AMICA NIKITA,BARBARA CHENEY,2,0.0,25.80,24.90,29.00" & vbCrLf _
	 & "3,N,LAURIE'S STAR,LAWRENCE REFAL,3,0.0,2.30,2.10,3.20" & vbCrLf _
	 & "4,Y,ROCA BENNY,ROBERT WHITELA,4,0.0,0.01,0.01,0.01" & vbCrLf _
	 & "5,N,SPICEY SPY,LESLIE FLETCHE,5,0.0,16.00,17.90,12.30" & vbCrLf _
	 & "6,Y,ASHBY JEWEL,KEVIN ELLIOTT,6,0.0,0.01,0.01,0.01" & vbCrLf _
	 & "7,N,MUNDINE,HELEN SIMMONS,7,0.0,4.40,4.30,4.10" & vbCrLf _
	 & "8,N,MINER BRUSHES,WENDY BROWN,8,0.0,14.40,15.90,13.10" & vbCrLf _
	 & "9,Y,TURTLE NECK,WAYNE VANDERBU,0,0.0,0.01,0.01,0.01" & vbCrLf _
	 & "10,N,BOO BOO LEE,KRISTY SULTANA,4,0.0,3.80,4.30,3.20" & vbCrLf _
	 & "W, , , , , ,26507,22505,10795" & vbCrLf _
	 & "P, , , , , ,5101,4407,2921" & vbCrLf _
	 & "Q, , , , , ,2524,2197,1681" & vbCrLf _
	 & "E, , , , , ,1210,1095,816" & vbCrLf _
	 & "T, , , , , ,6998,6278,4823" & vbCrLf _
	 & "F, , , , , ,0,0,0" & vbCrLf _
	 & "D, , , , , ,0,0,0" & vbCrLf _
	 & "R, , , , , ,0,0,0" & vbCrLf _
	 & "4, , , , , ,0,0,0" & vbCrLf _
	 & "." & vbCrLf _
	 & ""

	Private Sub OnLoad(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
		Try
			Races = New SortableBindingList2(Of RaceInfo)
			RaceSource.DataSource = Races
			RunnerListViewData(data)
			ObjectListView1.DataSource = RaceSource
			TypedList = New TypedObjectListView(Of RaceInfo)(ObjectListView1)
			TypedList.GenerateAspectGetters()
			ObjectListView1.Sort(colWinOdds, SortOrder.Descending)
		Catch ex As Exception

		End Try
	End Sub

	Public Sub RunnerListViewData(ByVal data As String)
		Try
			Dim raceInfo As String() = data.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
			Dim numRaces As Integer
			If raceInfo.Length > 3 Then
				With raceInfo(2)
					If Integer.TryParse(raceInfo(2).Split(New Char() {","c})(1), numRaces) Then
						For i = 3 To numRaces + 2
							With raceInfo(i)
								Dim parts As String() = raceInfo(i).Split(New Char() {","c})
								Dim info As New RaceInfo()
								If parts(0) Is Nothing OrElse Not Integer.TryParse(parts(0), info.Number) Then
									info = Nothing
								Else
									If parts(6) Is Nothing OrElse Not Decimal.TryParse(parts(6), info.WinOdds) Then
										info = Nothing
									End If
								End If
								If Not info Is Nothing Then
									AddHandler info.CheckChanged, AddressOf OnCheckChanged
									Races.Add(info)
								End If
							End With
						Next
					End If
				End With
			End If
		Catch ex As Exception

		End Try
	End Sub

	Private Sub OnCheckChanged(ByVal sender As Object, ByVal e As CheckChangedEventArgs)
		If TypeOf (sender) Is RaceInfo Then
			Dim data As RaceInfo = CType(sender, RaceInfo)
			Select Case e.PropertyName
				Case "Check1"
					If e.PropertyValue Then
						data.MM = "MM Calculation"
						data.PoolPercentage = 34.28
					Else
						data.MM = String.Empty
						data.PoolPercentage = 0.0
					End If
				Case "Check2"
					If e.PropertyValue Then
						data.MG = "MG Calculation"
						data.RunningPercentage = 52.16
					Else
						data.MG = String.Empty
						data.PoolPercentage = 0.0
					End If
				Case "Check3"
					If e.PropertyValue Then
						data.RM = "RM Calculation"
						data.UDiff = data.PoolPercentage - data.RunningPercentage
					Else
						data.RM = String.Empty
						data.UDiff = String.Empty
					End If
			End Select
		End If
	End Sub

	''' <summary>Handles the <see cref="E:Click" /> event.</summary>
	''' <param name="sender">The sender.</param>
	''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
	Private Sub OnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnReload.Click, btnClear.Click, btnEdit.Click
		If TypeOf sender Is Button Then
			Dim btn As Button = DirectCast(sender, Button)
			If btn.Equals(btnClear) Then
				ObjectListView1.RemoveObjects(Races)
			End If

			If btn.Equals(btnReload) Then
				ObjectListView1.SetObjects(Races)
			End If

			If btn.Equals(btnEdit) Then
				Dim editor As RaceData = Nothing
				Dim race As RaceInfo = Nothing
				If ObjectListView1.SelectedObject IsNot Nothing AndAlso TypeOf ObjectListView1.SelectedObject Is RaceInfo Then
					race = DirectCast(ObjectListView1.SelectedObject, RaceInfo)
				Else
					race = New RaceInfo() With {.Number = Races.Max(Function(item) item.Number) + 1}
				End If

				editor = New RaceData(race)
				If editor.ShowDialog() = DialogResult.OK Then
					If ObjectListView1.SelectedObject Is Nothing Then
						Races.Add(editor.Race)
					End If
				End If
				If ObjectListView1.PrimarySortColumn IsNot Nothing Then
					If ObjectListView1.PrimarySortOrder = SortOrder.Ascending Then
						RaceSource.Sort = String.Format("{0} DESC", ObjectListView1.PrimarySortColumn.AspectName)
						RaceSource.Sort = String.Format("{0} ASC", ObjectListView1.PrimarySortColumn.AspectName)
					ElseIf ObjectListView1.PrimarySortOrder = SortOrder.Descending Then
						RaceSource.Sort = String.Format("{0} ASC", ObjectListView1.PrimarySortColumn.AspectName)
						RaceSource.Sort = String.Format("{0} DESC", ObjectListView1.PrimarySortColumn.AspectName)
					End If
				End If
			End If
		End If
	End Sub

	Private Sub OnBeforeSorting(ByVal sender As Object, ByVal e As BeforeSortingEventArgs) Handles ObjectListView1.BeforeSorting
		If Not IsSorting Then
			IsSorting = True
			e.Handled = True
			RaceSource.Sort = String.Format("{0} {1}", e.ColumnToSort.AspectName, If(e.SortOrder = SortOrder.None, String.Empty, If(e.SortOrder = SortOrder.Ascending, "ASC", "DESC")))
			IsSorting = False
		End If
	End Sub

	Private Sub OnListChanged(ByVal sender As Object, ByVal e As ListChangedEventArgs) Handles RaceSource.ListChanged
		If ObjectListView1.PrimarySortColumn IsNot Nothing Then
			If ObjectListView1.PrimarySortOrder = SortOrder.Ascending Then
				ObjectListView1.Sort(ObjectListView1.PrimarySortColumn, SortOrder.Descending)
				ObjectListView1.Sort(ObjectListView1.PrimarySortColumn, SortOrder.Ascending)
			ElseIf ObjectListView1.PrimarySortOrder = SortOrder.Descending Then
				ObjectListView1.Sort(ObjectListView1.PrimarySortColumn, SortOrder.Ascending)
				ObjectListView1.Sort(ObjectListView1.PrimarySortColumn, SortOrder.Descending)
			End If
		End If
	End Sub
End Class

Public Class RaceInfo
#Region "Check Changed Event Handlers"
	Private ReadOnly _checkChangedEventHandlers As New List(Of CheckChangedEventHandler)
	Public Custom Event CheckChanged As CheckChangedEventHandler
		AddHandler(ByVal value As CheckChangedEventHandler)
			_checkChangedEventHandlers.Add(value)
		End AddHandler

		RemoveHandler(ByVal value As CheckChangedEventHandler)
			_checkChangedEventHandlers.Remove(value)
		End RemoveHandler

		RaiseEvent(ByVal sender As Object, ByVal e As CheckChangedEventArgs)
			For Each handler As CheckChangedEventHandler In _checkChangedEventHandlers
				Try
					handler.Invoke(sender, e)
				Catch ex As Exception
					Debug.WriteLine(String.Format("Exception while invoking event handler: {0}", ex))
				End Try
			Next
		End RaiseEvent
	End Event

	Protected Overridable Sub OnCheckChanged(ByVal sender As Object, ByVal e As CheckChangedEventArgs)
		RaiseEvent CheckChanged(sender, e)
	End Sub
#End Region

#Region "Private Fields"
	Private fCheck1 As Boolean
	Private fCheck2 As Boolean
	Private fCheck3 As Boolean
	Private fMG As String
	Private fMM As String
	Private fNumber As Integer
	Private fPoolPercentage As Decimal
	Private fRM As String
	Private fRunningPercentage As Decimal
	Private fUDiff As String
	Private fWinOdds As Decimal
#End Region

#Region "Public Properties"
	Public Property Number() As Integer
		Get
			Return fNumber
		End Get
		Set(ByVal value As Integer)
			fNumber = value
			UpdateChecks()
		End Set
	End Property

	Public Property WinOdds() As Decimal
		Get
			Return fWinOdds
		End Get
		Set(ByVal value As Decimal)
			fWinOdds = value
			UpdateChecks()
		End Set
	End Property

	Public Property PoolPercentage() As Decimal
		Get
			Return fPoolPercentage
		End Get
		Set(ByVal value As Decimal)
			fPoolPercentage = value
			UpdateChecks()
		End Set
	End Property

	Public Property RunningPercentage() As Decimal
		Get
			Return fRunningPercentage
		End Get
		Set(ByVal value As Decimal)
			fRunningPercentage = value
			UpdateChecks()
		End Set
	End Property

	Public Property MM() As String
		Get
			Return fMM
		End Get
		Set(ByVal value As String)
			fMM = value
			UpdateChecks()
		End Set
	End Property

	Public Property UDiff() As String
		Get
			Return fUDiff
		End Get
		Set(ByVal value As String)
			fUDiff = value
			UpdateChecks()
		End Set
	End Property

	Public Property MG() As String
		Get
			Return fMG
		End Get
		Set(ByVal value As String)
			fMG = value
			UpdateChecks()
		End Set
	End Property

	Public Property RM() As String
		Get
			Return fRM
		End Get
		Set(ByVal value As String)
			fRM = value
			UpdateChecks()
		End Set
	End Property

	Public Property Check1() As Boolean
		Get
			Return fCheck1
		End Get
		Set(ByVal value As Boolean)
			If Not value.Equals(fCheck1) Then
				fCheck1 = value
				RaiseEvent CheckChanged(Me, New CheckChangedEventArgs("Check1", Check1))
			End If
		End Set
	End Property

	Public Property Check2() As Boolean
		Get
			Return fCheck2
		End Get
		Set(ByVal value As Boolean)
			If Not value.Equals(fCheck2) Then
				fCheck2 = value
				RaiseEvent CheckChanged(Me, New CheckChangedEventArgs("Check2", Check2))
			End If
		End Set
	End Property

	Public Property Check3() As Boolean
		Get
			Return fCheck3
		End Get
		Set(ByVal value As Boolean)
			If Not value.Equals(fCheck3) Then
				fCheck3 = value
				RaiseEvent CheckChanged(Me, New CheckChangedEventArgs("Check3", Check3))
			End If
		End Set
	End Property
#End Region

#Region "Private Methods"
	Private Sub UpdateChecks()
		If fWinOdds > 15 Then
			Check3 = True
		End If
	End Sub
#End Region
End Class

<Serializable()> _
Public Class SortableBindingList2(Of T)
	Inherits BindingList(Of T)
	Private _isSorted As Boolean
	Private _dir As ListSortDirection = ListSortDirection.Ascending

	<NonSerialized()> _
	Private _sort As PropertyDescriptor = Nothing

	Sub New(ByVal list As ICollection(Of T))
		MyBase.New(CType(list, IList(Of T)))
	End Sub

	Sub New()
		MyBase.New()
	End Sub

#Region "BindingList<T> Public Sorting API"
	Public Sub Sort()
		ApplySortCore(_sort, _dir)
	End Sub

	Public Sub Sort(ByVal [property] As String)
		' Get the PD 

		_sort = FindPropertyDescriptor([property])

		' Sort 

		ApplySortCore(_sort, _dir)
	End Sub

	Public Sub Sort(ByVal [property] As String, ByVal direction As ListSortDirection)
		' Get the sort property 

		_sort = FindPropertyDescriptor([property])
		_dir = direction

		' Sort 

		ApplySortCore(_sort, _dir)
	End Sub
#End Region

#Region "BindingList<T> Sorting Overrides"
	Protected Overrides ReadOnly Property SortDirectionCore() As ListSortDirection
		Get
			Return _dir
		End Get
	End Property

	Protected Overrides ReadOnly Property SortPropertyCore() As PropertyDescriptor
		Get
			Return _sort
		End Get
	End Property

	Protected Overrides ReadOnly Property SupportsSortingCore() As Boolean
		Get
			Return True
		End Get
	End Property

	Protected Overrides Sub ApplySortCore(ByVal [property] As PropertyDescriptor, ByVal direction As ListSortDirection)
		Dim items As List(Of T) = TryCast(Me.Items, List(Of T))

		If (items IsNot Nothing) AndAlso ([property] IsNot Nothing) Then
			Dim pc As New PropertyComparer(Of T)([property], direction)
			items.Sort(pc)

			' Set sorted 

			_isSorted = True
			_sort = [property]
			_dir = direction
		Else
			' Set sorted 

			_isSorted = False
		End If

		' Let bound controls know they should refresh their views
		Me.OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, -1))
	End Sub

	Protected Overrides ReadOnly Property IsSortedCore() As Boolean
		Get
			Return _isSorted
		End Get
	End Property

	Protected Overrides Sub RemoveSortCore()
		_isSorted = False
	End Sub
#End Region

#Region "BindingList<T> Private Sorting API"
	Private Function FindPropertyDescriptor(ByVal [property] As String) As PropertyDescriptor
		Dim pdc As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
		Dim prop As PropertyDescriptor = Nothing

		If pdc IsNot Nothing Then
			prop = pdc.Find([property], True)
		End If

		Return prop
	End Function
#End Region

#Region "PropertyComparer<TKey>"
	Friend Class PropertyComparer(Of TKey)
		Implements System.Collections.Generic.IComparer(Of TKey)
		'
		'			* The following code contains code implemented by Rockford Lhotka:
		'			* //msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet/html/vbnet01272004.asp" href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet/html/vbnet01272004.asp">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet/html/vbnet01272004.asp
		'			


		Private _property As PropertyDescriptor
		Private _direction As ListSortDirection

		Public Sub New(ByVal [property] As PropertyDescriptor, ByVal direction As ListSortDirection)
			_property = [property]
			_direction = direction
		End Sub

		Public Function Compare(ByVal xVal As TKey, ByVal yVal As TKey) As Integer Implements IComparer(Of TKey).Compare
			' Get property values 

			Dim xValue As Object = GetPropertyValue(xVal, _property.Name)
			Dim yValue As Object = GetPropertyValue(yVal, _property.Name)

			' Determine sort order 

			If _direction = ListSortDirection.Ascending Then
				Return CompareAscending(xValue, yValue)
			Else
				Return CompareDescending(xValue, yValue)
			End If
		End Function

		Public Function Equals(ByVal xVal As TKey, ByVal yVal As TKey) As Boolean
			Return xVal.Equals(yVal)
		End Function

		Public Function GetHashCode(ByVal obj As TKey) As Integer
			Return obj.GetHashCode()
		End Function

		' Compare two property values of any type 

		Private Function CompareAscending(ByVal xValue As Object, ByVal yValue As Object) As Integer
			Dim result As Integer

			' If values implement IComparer 

			If TypeOf xValue Is IComparable Then
				result = DirectCast(xValue, IComparable).CompareTo(yValue)
				' If values don't implement IComparer but are equivalent 

			ElseIf xValue.Equals(yValue) Then
				result = 0
			Else
				' Values don't implement IComparer and are not equivalent, so compare as string values 

				result = xValue.ToString().CompareTo(yValue.ToString())
			End If

			' Return result 

			Return result
		End Function

		Private Function CompareDescending(ByVal xValue As Object, ByVal yValue As Object) As Integer
			' Return result adjusted for ascending or descending sort order ie
			'				   multiplied by 1 for ascending or -1 for descending 

			Return CompareAscending(xValue, yValue) * -1
		End Function

		Private Function GetPropertyValue(ByVal value As TKey, ByVal [property] As String) As Object
			' Get property 

			Dim propertyInfo As PropertyInfo = value.[GetType]().GetProperty([property])

			' Return value 

			Return propertyInfo.GetValue(value, Nothing)
		End Function
	End Class
#End Region
End Class

Public Class SortableBindingList(Of T)
	Inherits BindingList(Of T)
	Private Property IsSorted As Boolean
	Private Property SortDirection As ListSortDirection
	Private Property SortProperty As PropertyDescriptor

	Protected Overrides ReadOnly Property SupportsSortingCore() As Boolean
		Get
			Return True
		End Get
	End Property

	Protected Overrides ReadOnly Property SortDirectionCore() As ListSortDirection
		Get
			Return _SortDirection
		End Get
	End Property

	Protected Overrides ReadOnly Property SortPropertyCore() As PropertyDescriptor
		Get
			Return _SortProperty
		End Get
	End Property

	Protected Overrides Sub ApplySortCore(ByVal [property] As PropertyDescriptor, ByVal direction As ListSortDirection)
		Dim items As List(Of T) = TryCast(Me.Items, List(Of T))
		If items Is Nothing Then
			IsSorted = False
		Else
			Dim comparer As New PropertyCompare(Of T)([property].Name, direction)
			items.Sort(comparer)
			IsSorted = True
			SortDirection = direction
			SortProperty = [property]
		End If
		OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, -1))
	End Sub

	Protected Overrides ReadOnly Property IsSortedCore() As Boolean
		Get
			Return _IsSorted
		End Get
	End Property

	Protected Overrides Sub RemoveSortCore()
		_IsSorted = False
	End Sub

	Sub New(ByVal list As ICollection(Of T))
		MyBase.New(CType(list, IList(Of T)))
	End Sub

	Sub New()
		MyBase.New()
	End Sub

	Private Class PropertyCompare(Of T)
		Implements IComparer(Of T)

		Private Property PropertyInfo() As PropertyInfo
		Private Property SortDirection() As ListSortDirection
		Friend Sub New(ByVal [property] As String, ByVal direction As ListSortDirection)
			PropertyInfo = GetType(T).GetProperty([property])
			SortDirection = direction
		End Sub

		Friend Function Compare(ByVal x As T, ByVal y As T) As Integer Implements IComparer(Of T).Compare
			Return If(SortDirection = ListSortDirection.Ascending,
			  Comparer.[Default].Compare(PropertyInfo.GetValue(x, Nothing), PropertyInfo.GetValue(y, Nothing)),
			  Comparer.[Default].Compare(PropertyInfo.GetValue(y, Nothing), PropertyInfo.GetValue(x, Nothing)))
		End Function
	End Class
End Class

Public Delegate Sub CheckChangedEventHandler(ByVal sender As Object, ByVal e As CheckChangedEventArgs)

Public Class CheckChangedEventArgs
	Inherits EventArgs
	Private ReadOnly _propertyName As String
	Public ReadOnly Property PropertyName() As String
		Get
			Return _propertyName
		End Get
	End Property

	Private ReadOnly _propertyValue As Boolean
	Public ReadOnly Property PropertyValue() As Boolean
		Get
			Return _propertyValue
		End Get
	End Property

	Private Sub New()

	End Sub

	Public Sub New(ByVal PropertyName As String, ByVal PropertyValue As Boolean)
		_propertyName = PropertyName
		_propertyValue = PropertyValue
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
	Inherits System.Windows.Forms.Form

	'Form overrides dispose to clean up the component list.
	<System.Diagnostics.DebuggerNonUserCode()> _
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)
		Try
			If disposing AndAlso components IsNot Nothing Then
				components.Dispose()
			End If
		Finally
			MyBase.Dispose(disposing)
		End Try
	End Sub

	'Required by the Windows Form Designer
	Private components As System.ComponentModel.IContainer

	'NOTE: The following procedure is required by the Windows Form Designer
	'It can be modified using the Windows Form Designer.  
	'Do not modify it using the code editor.
	<System.Diagnostics.DebuggerStepThrough()> _
	Private Sub InitializeComponent()
		Me.components = New System.ComponentModel.Container()
		Me.ObjectListView1 = New BrightIdeasSoftware.DataListView()
		Me.colNumber = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colWinOdds = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colPoolPercentage = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colRunningPercentage = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colMM = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colUDiff = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colMG = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colRM = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colCheck1 = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colCheck2 = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.colCheck3 = CType(New BrightIdeasSoftware.OLVColumn(), BrightIdeasSoftware.OLVColumn)
		Me.btnClear = New System.Windows.Forms.Button()
		Me.btnReload = New System.Windows.Forms.Button()
		Me.btnEdit = New System.Windows.Forms.Button()
		Me.RaceSource = New System.Windows.Forms.BindingSource(Me.components)
		CType(Me.ObjectListView1, System.ComponentModel.ISupportInitialize).BeginInit()
		CType(Me.RaceSource, System.ComponentModel.ISupportInitialize).BeginInit()
		Me.SuspendLayout()
		'
		'ObjectListView1
		'
		Me.ObjectListView1.AllColumns.Add(Me.colNumber)
		Me.ObjectListView1.AllColumns.Add(Me.colWinOdds)
		Me.ObjectListView1.AllColumns.Add(Me.colPoolPercentage)
		Me.ObjectListView1.AllColumns.Add(Me.colRunningPercentage)
		Me.ObjectListView1.AllColumns.Add(Me.colMM)
		Me.ObjectListView1.AllColumns.Add(Me.colUDiff)
		Me.ObjectListView1.AllColumns.Add(Me.colMG)
		Me.ObjectListView1.AllColumns.Add(Me.colRM)
		Me.ObjectListView1.AllColumns.Add(Me.colCheck1)
		Me.ObjectListView1.AllColumns.Add(Me.colCheck2)
		Me.ObjectListView1.AllColumns.Add(Me.colCheck3)
		Me.ObjectListView1.AllowColumnReorder = True
		Me.ObjectListView1.AllowDrop = True
		Me.ObjectListView1.AlternateRowBackColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(240, Byte), Integer), CType(CType(220, Byte), Integer))
		Me.ObjectListView1.BackColor = System.Drawing.SystemColors.Window
		Me.ObjectListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.colNumber, Me.colWinOdds, Me.colPoolPercentage, Me.colRunningPercentage, Me.colMM, Me.colUDiff, Me.colMG, Me.colRM, Me.colCheck1, Me.colCheck2, Me.colCheck3})
		Me.ObjectListView1.Cursor = System.Windows.Forms.Cursors.Default
		Me.ObjectListView1.DataSource = Nothing
		Me.ObjectListView1.EmptyListMsg = "This list is empty."
		Me.ObjectListView1.FullRowSelect = True
		Me.ObjectListView1.Location = New System.Drawing.Point(13, 13)
		Me.ObjectListView1.Name = "ObjectListView1"
		Me.ObjectListView1.OwnerDraw = True
		Me.ObjectListView1.Size = New System.Drawing.Size(655, 237)
		Me.ObjectListView1.TabIndex = 0
		Me.ObjectListView1.UseAlternatingBackColors = True
		Me.ObjectListView1.UseCompatibleStateImageBehavior = False
		Me.ObjectListView1.View = System.Windows.Forms.View.Details
		'
		'colNumber
		'
		Me.colNumber.AspectName = "Number"
		Me.colNumber.Groupable = False
		Me.colNumber.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colNumber.Text = "Race #"
		Me.colNumber.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colNumber.Width = 70
		'
		'colWinOdds
		'
		Me.colWinOdds.AspectName = "WinOdds"
		Me.colWinOdds.Groupable = False
		Me.colWinOdds.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colWinOdds.Text = "Win Odds"
		Me.colWinOdds.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
		Me.colWinOdds.Width = 70
		'
		'colPoolPercentage
		'
		Me.colPoolPercentage.AspectName = "PoolPercentage"
		Me.colPoolPercentage.Groupable = False
		Me.colPoolPercentage.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colPoolPercentage.Text = "Pool %"
		Me.colPoolPercentage.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
		Me.colPoolPercentage.Width = 70
		'
		'colRunningPercentage
		'
		Me.colRunningPercentage.AspectName = "RunningPercentage"
		Me.colRunningPercentage.Groupable = False
		Me.colRunningPercentage.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Right
		Me.colRunningPercentage.Text = "Running %"
		Me.colRunningPercentage.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
		Me.colRunningPercentage.Width = 70
		'
		'colMM
		'
		Me.colMM.AspectName = "MM"
		Me.colMM.Groupable = False
		Me.colMM.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colMM.Text = "MM"
		Me.colMM.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colMM.Width = 70
		'
		'colUDiff
		'
		Me.colUDiff.AspectName = "UDiff"
		Me.colUDiff.Groupable = False
		Me.colUDiff.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colUDiff.Text = "UDiff"
		Me.colUDiff.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colUDiff.Width = 70
		'
		'colMG
		'
		Me.colMG.AspectName = "MG"
		Me.colMG.Groupable = False
		Me.colMG.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colMG.Text = "MG"
		Me.colMG.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colMG.Width = 70
		'
		'colRM
		'
		Me.colRM.AspectName = "RM"
		Me.colRM.Groupable = False
		Me.colRM.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colRM.Text = "RM"
		Me.colRM.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colRM.Width = 70
		'
		'colCheck1
		'
		Me.colCheck1.AspectName = "Check1"
		Me.colCheck1.CheckBoxes = True
		Me.colCheck1.Groupable = False
		Me.colCheck1.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colCheck1.Text = "1"
		Me.colCheck1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colCheck1.Width = 30
		'
		'colCheck2
		'
		Me.colCheck2.AspectName = "Check2"
		Me.colCheck2.CheckBoxes = True
		Me.colCheck2.Groupable = False
		Me.colCheck2.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colCheck2.Text = "2"
		Me.colCheck2.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colCheck2.Width = 30
		'
		'colCheck3
		'
		Me.colCheck3.AspectName = "Check3"
		Me.colCheck3.CheckBoxes = True
		Me.colCheck3.Groupable = False
		Me.colCheck3.HeaderTextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colCheck3.Text = "3"
		Me.colCheck3.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
		Me.colCheck3.Width = 30
		'
		'btnClear
		'
		Me.btnClear.Location = New System.Drawing.Point(512, 270)
		Me.btnClear.Name = "btnClear"
		Me.btnClear.Size = New System.Drawing.Size(75, 23)
		Me.btnClear.TabIndex = 1
		Me.btnClear.Text = "Clear"
		Me.btnClear.UseVisualStyleBackColor = True
		'
		'btnReload
		'
		Me.btnReload.Location = New System.Drawing.Point(593, 270)
		Me.btnReload.Name = "btnReload"
		Me.btnReload.Size = New System.Drawing.Size(75, 23)
		Me.btnReload.TabIndex = 2
		Me.btnReload.Text = "Reload"
		Me.btnReload.UseVisualStyleBackColor = True
		'
		'btnEdit
		'
		Me.btnEdit.Location = New System.Drawing.Point(431, 270)
		Me.btnEdit.Name = "btnEdit"
		Me.btnEdit.Size = New System.Drawing.Size(75, 23)
		Me.btnEdit.TabIndex = 3
		Me.btnEdit.Text = "Add/Edit Races"
		Me.btnEdit.UseVisualStyleBackColor = True
		'
		'RaceSource
		'
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(681, 305)
		Me.Controls.Add(Me.btnEdit)
		Me.Controls.Add(Me.btnReload)
		Me.Controls.Add(Me.btnClear)
		Me.Controls.Add(Me.ObjectListView1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.ObjectListView1, System.ComponentModel.ISupportInitialize).EndInit()
		CType(Me.RaceSource, System.ComponentModel.ISupportInitialize).EndInit()
		Me.ResumeLayout(False)

	End Sub
	Friend WithEvents ObjectListView1 As BrightIdeasSoftware.DataListView
	Friend WithEvents colNumber As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colRunningPercentage As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colMM As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colUDiff As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colMG As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colRM As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colCheck1 As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colCheck2 As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colCheck3 As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colPoolPercentage As BrightIdeasSoftware.OLVColumn
	Friend WithEvents colWinOdds As BrightIdeasSoftware.OLVColumn
	Friend WithEvents btnClear As System.Windows.Forms.Button
	Friend WithEvents btnReload As System.Windows.Forms.Button
	Friend WithEvents RaceSource As System.Windows.Forms.BindingSource
	Friend WithEvents btnEdit As System.Windows.Forms.Button

End Class

Open in new window

Produces the following output -Capture.JPG-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JasonAuthor Commented:
Hi Saige

Thanks again can work with that

Great

Cheers
Jason
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

JasonAuthor Commented:
On thing RaceData not defines
0
JasonAuthor Commented:
Having troubles tiring in the money gap process
Can you assist.

The process id dependent on the fWinOdds column being sorted before calculations being done

Here is my code
    Sub ProcessMoneyGap()
        For ic As Integer = 0 To Form1.ObjectListView1.Items.Count - 1
            If ic <> Form1.ObjectListView1.Items.Count - 1 Then
                Dim OldVal = Form1.ObjectListView1.Items(ic).SubItems(0).Text
                Dim NewVal = Form1.ObjectListView1.Items(ic + 1).SubItems(0).Text
                Dim Cp = Math.Round(((NewVal - OldVal) / OldVal) + 1, 2, MidpointRounding.AwayFromZero)
                Dim CalcPercent = Math.Round(((NewVal - OldVal) / OldVal * 100), 2, MidpointRounding.AwayFromZero)
                Form1.ObjectListView1.Items(ic).SubItems(6).Text = Cp '& " / " & CalcPercent
            End If
        Next
        Dim count
        For Each sb As OLVListItem In Form1.ObjectListView1.Items
            If sb.SubItems(6).Text <> "" Then
                If sb.SubItems(6).Text >= 1.5 Then
                    If count < 3 Then
                        sb.UseItemStyleForSubItems = False
                        sb.SubItems(6).ForeColor = Color.Red
                        count += 1
                        If count = 1 Then
                            For u = 0 To 10
                                sb.SubItems(u).BackColor = Color.LightGreen
                            Next
                        ElseIf count = 2 Then
                            For u = 0 To 10
                                sb.SubItems(u).BackColor = Color.LightSalmon
                            Next
                        ElseIf count = 3 Then
                            For u = 0 To 10
                                sb.SubItems(u).BackColor = Color.LightSteelBlue
                            Next
                        ElseIf count <> 1 Or count <> 2 Or count <> 3 Then
                            For u = 0 To 10
                                sb.SubItems(u).BackColor = Color.Transparent
                            Next
                        End If
                    ElseIf count <> 1 Or count <> 2 Or count <> 3 Then
                        For u = 0 To 10
                            sb.SubItems(u).BackColor = Color.Transparent
                        Next
                    End If
                Else
                    sb.UseItemStyleForSubItems = False
                    sb.SubItems(6).ForeColor = Color.Black
                End If
            End If
        Next
    End Sub

Open in new window

0
it_saigeDeveloperCommented:
You need to change the properties of the object that the row is built from, not the fields/cells/columns in the row.

-saige-
0
JasonAuthor Commented:
I dont quiet understand
Could you give me an example
The problem im having is in order for  me to calculate the gap or difference it needs to exist first for me to use.
Ie row (0) money  gap need to know what  the odds are for  that row which is  is easy  but also that next row (1)
0
it_saigeDeveloperCommented:
Ok, so then for example:
Sub ProcessMoneyGap()
	For ic As Integer = 0 To ObjectListView1.Items.Count - 1
		If ic <> ObjectListView1.Items.Count - 1 Then
			Dim OldVal = CType(CType(ObjectListView1.Items(ic), OLVListItem).RowObject, RaceInfo)
			Dim NewVal = CType(CType(ObjectListView1.Items(ic + 1), OLVListItem).RowObject, RaceInfo)
			Dim Cp = Math.Round(((NewVal.WinOdds - OldVal.WinOdds) / OldVal.WinOdds) + 1, 2, MidpointRounding.AwayFromZero)
			Dim CalcPercent = Math.Round(((NewVal.WinOdds - OldVal.WinOdds) / OldVal.WinOdds * 100), 2, MidpointRounding.AwayFromZero)
			OldVal.MG = Cp '& " / " & CalcPercent
		End If
	Next
	Dim count
	For Each sb As OLVListItem In ObjectListView1.Items
		If sb.SubItems(6).Text <> "" Then
			If sb.SubItems(6).Text >= 1.5 Then
				If count < 3 Then
					sb.UseItemStyleForSubItems = False
					sb.SubItems(6).ForeColor = Color.Red
					count += 1
					If count = 1 Then
						For u = 0 To 10
							sb.SubItems(u).BackColor = Color.LightGreen
						Next
					ElseIf count = 2 Then
						For u = 0 To 10
							sb.SubItems(u).BackColor = Color.LightSalmon
						Next
					ElseIf count = 3 Then
						For u = 0 To 10
							sb.SubItems(u).BackColor = Color.LightSteelBlue
						Next
					ElseIf count <> 1 Or count <> 2 Or count <> 3 Then
						For u = 0 To 10
							sb.SubItems(u).BackColor = Color.Transparent
						Next
					End If
				ElseIf count <> 1 Or count <> 2 Or count <> 3 Then
					For u = 0 To 10
						sb.SubItems(u).BackColor = Color.Transparent
					Next
				End If
			Else
				sb.UseItemStyleForSubItems = False
				sb.SubItems(6).ForeColor = Color.Black
			End If
		End If
	Next
End Sub

Open in new window

-saige-
0
JasonAuthor Commented:
Great thx
I am slowly understanding how to use this control
0
JasonAuthor Commented:
Saige

Having 2 problems

See Pic
Can you explain how I can get sort to work in module.  Works fine if I place it in form1 but not under any other module.

Untitledjj.png
secondly
When I run code to alter through the program checkbox ticks are not visible.

would you know why????
Untitledlklj.png
0
it_saigeDeveloperCommented:
Because the module does not know about the objects on the form.  Thats why olv1WOdds has the squiggly line underneath it.

Probably because you are not modifying the underlying object that makes up the row.

-saige-
0
JasonAuthor Commented:
solved the first one

any clue on the second one.
when i use the fwinodds tick appear in listview but if i change to fmg then objects in raceinfo indicated true value but the ticks dont appear on the screen.  
what is funny is if i click on the true check box it activates all that were true for that row.

any help would  be greatly appreciated
0
JasonAuthor Commented:
Saige
It appear that ticks dont work in checkboxes under a edit situation you  have to call the entire process
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.