I am using the code below to determine the selected index of multiple combo boxes, although for some reason my if statement is not working correctly. If the boolean portion returns false, it still "processes" the true portion creating an error.
So for example, If the number of sort keys returns 1 that means is IIF statement should return 0. Although instead a error is thrown, because MyGrid.SortKeys(1).Index does not exist, because the count of SortKeys are not large enough. Why would it attempt to processes the true portion
Me
.ComboTwo.SelectedIndex = IIf(MyGrid.SortKeys.Count >= 2, MyGrid.SortKeys(1).Index + 1, 0)
IIF Statement Question
Mark1212
The fact that your telling me that an exception is thrown is the reason why its not working. The IIF cannot evaluate if it is true or false as an exception has occured. The expression simply cannot be evaluated. This is expected bahaviour
If you want to have the item set to 0 if an exception occurs then simply wrap it in a function.
I'm not using the grid control but can achieve a similar effect with a textbox. With the SetIndex function if I enter a text value which is not convertable to an integer - such as the letter a it will throw and exception in the setindex function which would cause a default value of 0 to be returned.
Now this is not good practice to use exception handling to control program flow - it is better to write validation code in you code. In you case it would be to verify that Mygrid.sortkeys isnot nothing. But you can leave the exception in there just in case any strange and unexpected happens.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.ComboBox1.SelectedIndex = SetIndex()
End Sub
Function SetIndex() As Integer
Try
Return IIf(Me.TextBox1.Text >= 2, 1, 0)
Catch ex As Exception
Return 0
End Try
End Function
End Class
sweetpea7227
This is actually a limitation of IIf; it evaluates both true and false parts of the statement.
For more information, see the comment that I made at the bottom of the following topic: http://msdnwiki.microsoft.com/en-us/mtpswiki/27ydhh0d(vs.80).aspx.
Kalor
IIf(Expression, TruePart, FalsePart)
Dennis Joy
IIf is a method (in the VisualBasic.Interaction class). Like every other method available in every other class, all arguments are evaluated.
You're thinking of IIf as an operator - this is incorrect. IIf is not like the operator in C# for instance.
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
Instant C++: C# to C++ converter
Instant C++: VB to C++ converter
Clear VB: Cleans up VB.NET code