Bloggging about .NET tips, tricks, and so much more...!

Thursday, November 22, 2007

Control Array using VB.NET 2005

Public Class clsControlArray
Public Shared Function getControlArray(ByVal frm As Windows.Forms.Form, ByVal controlName As String) As System.Array
Dim i As Short
Dim startOfIndex As Short
Dim alist As New ArrayList
Dim controlType As System.Type

Dim ctl As System.Windows.Forms.Control
Dim strSuffix As String
Dim maxIndex As Short = -1 'Default

'Loop through all controls, looking for controls with the matching name pattern
'Find the highest indexed control
Dim allControls As ArrayList = GatherAllControls(frm)

For Each ctl In allControls
startOfIndex = ctl.Name.ToLower.IndexOf(controlName.ToLower)
If startOfIndex = 0 Then
strSuffix = ctl.Name.Substring(controlName.Length)
If IsInteger(strSuffix) Then 'Check that the suffix is an integer (index of the array)
If Val(strSuffix) > maxIndex Then maxIndex = Val(strSuffix) 'Find the highest indexed Element
End If
End If
Next ctl

Return alist.ToArray(GetType(Control))
End Function

Private Shared Function getControlFromName(ByRef frm As Windows.Forms.Form, ByVal controlName As String, ByVal index As Short) As System.Windows.Forms.Control
controlName = controlName & index
For Each ctl As Control In frm.Controls
If String.Compare(ctl.Name, controlName, True) = 0 Then
Return ctl
End If
Next ctl

Return Nothing
End Function

Private Shared Function getControlFromName(ByVal allControls As ArrayList, ByVal controlName As String, ByVal index As Short) As System.Windows.Forms.Control

controlName = controlName & index
For Each ctl As Control In allControls
If String.Compare(ctl.Name, controlName, True) = 0 Then
Return ctl
End If
Next ctl

Return Nothing
End Function

Private Shared Function IsInteger(ByVal Value As String) As Boolean
If Value = "" Then Return False

For Each chr As Char In Value
If Not Char.IsDigit(chr) Then
Return False
End If
Next
Return True
End Function

End Class

No comments:

PRC Board Exam Results

Feeds from Jehzlau Concepts