JavascriptProva

mercoledì 21 agosto 2013

Una funzione per raccogliere in una ArrayList controlli dello stesso tipo con parte del nome uguale.

Ho elaborato una funzione che mi permette di inserire in una ArrayList tutti gli elementi che hanno uno stesso nome o parte del nome.
    Function CtrlByName(ByRef frm As Form, ByVal nome As String) As ArrayList
        Dim matrice As New ArrayList
        For Each elemento In frm.Controls
            Dim stringa As String = elemento.name
            Try
                If stringa.Substring(0, nome.Length) = nome Then matrice.Add(elemento)
            Catch ex As Exception
            End Try
        Next
        Return matrice
    End Function
La funzione è un ArrayList.
Ecco come viene usata:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lista As ArrayList
        lista = CtrlByName(Me, "TextBox")
        For n = 0 To lista.Count - 1
            lista(n).text = "Io faccio parte della matrice"
        Next
    End Sub
In questo modo la scritta "Io faccio parte della matrice" viene scritta solo nei controlli che hanno il nome che inizia per "TextBox".
Si potrebbe renderla più precisa limitandola per tipo di controlli (se il controllo non ha la proprietà Text si genererebbe un errore).

    Function CtrlByName(ByRef frm As Form, ByVal nome As String) As ArrayList
        Dim matrice As New ArrayList
        For Each elemento In frm.Controls
            Dim stringa As String = elemento.name
            Try
                If TypeOf elemento Is TextBox And stringa.Substring(0, nome.Length) = nome Then matrice.Add(elemento)
            Catch ex As Exception
            End Try
        Next
        Return matrice
    End Function
    
End Class
Ovviamente, il tipo deve essere flessibile, quindi andrebbe riportato fra i parametri...

Ecco risolto! Ovviamente, un tipo non si può passare come parametro, ma si può usare il generic:
    Function CtrlByName(Of T)(ByRef frm As Form, ByVal nome As String) As ArrayList
        Dim matrice As New ArrayList
        For Each elemento In frm.Controls
            Dim stringa As String = elemento.name
            Try
                If TypeOf elemento Is T And stringa.Substring(0, nome.Length) = nome Then matrice.Add(elemento)
            Catch ex As Exception
            End Try
        Next
        Return matrice
    End Function
Ed ecco come viene usata la funzione:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lista As ArrayList
        lista = CtrlByName(Of TextBox)(Me, "TextBox")
        For n = 0 To lista.Count - 1
            lista(n).text = "Io faccio parte della matrice"
        Next
    End Sub

Nessun commento:

Posta un commento