Equivalent For loops not working

njsokalski

Well-known member
Joined
Mar 16, 2011
Messages
102
Programming Experience
5-10
I have the constructor for a UserControl for a Windows Phone 7 App:
VB.NET:
Public Sub New(ByVal isodd As Boolean)
	Me.New()
	If (isodd) Then
		For Each txt As UIElement In CType(Me.Content, StackPanel).Children
			CType(txt, TextBox).BorderBrush = New SolidColorBrush(Colors.White)
		Next
	Else
		For Each txt As UIElement In CType(Me.Content, StackPanel).Children
			CType(txt, TextBox).BorderBrush = New SolidColorBrush(Colors.Black)
		Next
	End If
End Sub
You will notice that the only difference between the two for loops is that one uses White and one uses Black. However, the constructor is not working (my app will not start) with the code as is. My MainPage currently calls this constructor sending a value of False, and if I comment out the first For loop it will work. However, if I change the constructor to
VB.NET:
Public Sub New(ByVal isodd As Boolean)
	Me.New()
	If (Not isodd) Then
		For Each txt As UIElement In CType(Me.Content, StackPanel).Children
			CType(txt, TextBox).BorderBrush = New SolidColorBrush(Colors.White)
		Next
	Else
		'For Each txt As UIElement In CType(Me.Content, StackPanel).Children
		'	CType(txt, TextBox).BorderBrush = New SolidColorBrush(Colors.Black)
		'Next
	End If
End Sub
Note that I used Not so that it goes to the first For loop instead, and commented out the second For loop, it does not work when I do this. But shouldn't it work either way, since the For loops are the only statements in the constructor and are (almost) exactly the same? Does the constructor have something against the color White? Any help would be appreciated. Thanks.
 
Last edited by a moderator:
I've added [code] tags around your code snippets for readability. Please do so yourself in future.

First up, on the subject of style, you don't need two For Each loops. A more correct way to code that would be:
VB.NET:
Dim colour = If(isOdd, Colors.White, Colors.Black)
Dim brush As New SolidColorBrush(colour)

For Each txt As TextBox In DirectCast(Me.Context, StackPanel)
    txt.BorderBrush = brush
Next
That code contains much less repetition. Also, the cast as type TextBox is made in the For each statement itself, which is cleaner.

As for the question, if the code doesn't work then an exception must be thrown. That exception contains information about what went wrong. That's the first place to look.
 
I still don't know why mine didn't work, but changing the algorithm to your suggest did, so even if I still don't have an explanation, I do have a workaround/solution for now. Thanks!
 
Back
Top