Ben Williams
Ben Williams

Reputation: 131

asp.net vb Directcast Error

I'm trying to get the values from a dynamically created textbox(es) using an update panel. The line that keeps failing is:

strName = DirectCast(pnlVars.Controls(strNameString), TextBox).ToString

Error System.FormatException: Input string was not in a correct format.

The strNameString variable is created dynamically but is a string link fwID.

Here's the whole loop.

For i = 0 To strArr.Count - 1
        If i = 0 Then
            qtype = " WHERE "
        Else
            qtype = " AND "
        End If
        strNameString = strArr(i).ToString().Replace("[", "fw").Replace("]", "")

        strName = DirectCast(pnlVars.Controls(strNameString), TextBox).ToString

        If strName <> "" Or strName <> Nothing Then
            sb.Append(qtype & strArr(i).ToString() & " = '" & strName & "' ")
        End If
    Next

Any idea how to fix this? Thanks

Upvotes: 0

Views: 133

Answers (1)

the_lotus
the_lotus

Reputation: 12748

Try it on multiple line to see where the error is

   Dim tb As TextBox = DirectCast(pnlVars.Controls(strNameString), TextBox)
   strName = tb.Text

If the error is on the first line, look at the value inside strNameString and make sure it's properly formatted.

As you can also see, I didn't use ToString() this wouldn't return what you want. You want the text inside the textbox.

Make sure strName is an actual string and not something else. In vb.net, it's not recommended to prefix variable with their type.

If that's for a query, don't concatenate the data in your query. Use parameters!

Upvotes: 1

Related Questions