troubleshooting Question

VB/ASP.Net Collection with a For Each loop

Avatar of mascoloj
mascolojFlag for United States of America asked on
.NET ProgrammingASP.NETVisual Basic.NET
10 Comments1 Solution505 ViewsLast Modified:
I am trying to figure out how to use a For Each loop with a collection to access the information within. Currently when the code runs I get an error at the beginning of the For Each loop which states "Specified cast is not valid". All items in the collection are Strings though so the error is puzzling me.

Below is a sample of my code with some comments. The error is in the dbsql class (second code window below). Any help on this issue would be great.

Public Structure SQL_Elements
        Dim FieldName As String
        Dim FieldValue As String
        Dim FieldType As String
End Structure

Public SQLCollection As Collection

Protected Sub btnSave1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave1.Click

SQLCollection = New Collection() ' Creates a new Collection to store the SQL elements in
Dim Temp As SQL_Elements 'Creates a new empty structure to place the SQL elements in

        Temp.FieldName = "OtherProgramInvolvment"
        Temp.FieldValue = txtOtherProgramInvolvment.Text
        Temp.FieldType = "SQLDbType.nvarchar, (MAX)"

dbsql.sqlUpdate("TblReferral_Community", SQLCollection, "ID='" & Request.QueryString("RID") & "'")
End Sub

dbsql Class
Public Shared Sub sqlUpdate(ByVal SQLTable As String, ByVal SQLCollection As Collection, ByVal WhereClause As String)

 For Each Item In SQLCollection 'This line causes the error
            cmd.Parameters.Add(New SqlParameter("'" & "@" & Item.FieldName & "'", Item.FieldType))
            cmd.Parameters("'" & "@" & Item.FieldName & "'").Value = Item.FieldValue
            SetClauses = SetClauses & Item.FieldName & " = " & "@" & Item.FieldName
            If Not ItemCounting = SQLCollection.Count Then
                SetClauses = SetClauses & ","
            End If

End Sub
Easwaran Paramasivam
Senior Software Engineer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 10 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 10 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros