[Error] 'ListItem' to type 'String'

  • Thread starter Sparky Arbuckle
  • Start date
S

Sparky Arbuckle

I am looping through a listbox collection to build a SQL string that
will be used to delete items from a database. I have tried many
variances of the code below but have had no luck. The code below gives
an error:

Cast from type 'ListItem' to type 'String' is not valid.

When i do a response.write(s) the item at the top row displays
correctly. Here is the code I am using:

Private Sub btnDeleteDrawings_Click(ByVal ...)

Dim i As Integer = 0
Dim s As String = lbColumn2.Items(0).Text.ToString

Dim strSQL As String = "DELETE FROM tbl X Y Z Where "

For Each s In lbColumn2.Items '<- Error thrown here

strSQL += "Text = '" & s & "'"
lbColumn2.SelectedIndex = -1

If c > 1 Then
strSQL += " AND "
Else
strSQL += ";"
End If
lbColumn2.Items.Remove(s)

Next

End Sub
 
M

Marina

's' is declared as a string. Each thing in the Items collection returns a
ListItem. You can't assign a ListItem to a variable of type String.

Additionally, your code doesn't make sense. You are assigning 's' a value,
but then presumably ignoring it, because you are trying to reuse the
variable in the loop.

And lastly, you should not be modifying the contents of a collection in a
For Each loop. You can use a While loop, or a For loop counting down
backwards, if you want to remove items as you loop.
 
S

Sparky Arbuckle

This is my first project using a listbox in this manner. Nice attitude
Marina. Very helpful.
 
S

S. Justin Gengo

Sparky,

Here's what you need:

Dim lbColumn2 As ListBox

Private Sub btnDeleteDrawings_Click(ByVal ...)

Dim i As Integer = 0

Dim s As String = lbColumn2.Items(0).Text.ToString

Dim strSQL As System.Text.StringBuilder

strSQL.Append("DELETE FROM tbl X Y Z Where ")

For Each ListItem As ListItem In lbColumn2.Items

strSQL.Append("Text = '" & ListItem.Text & "'")

lbColumn2.SelectedIndex = -1

If c > 1 Then

strSQL.Append(" AND ")

Else

strSQL.Append(";")

End If

lbColumn2.Items.Remove(s)

Next

End Sub



I changed the strSQL object to a string builder. It's much more efficient
for lengthy concatenations like you're doing here. Get the string out of it
after the loop finishes like this: strSQL.ToString




--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 
S

Sparky Arbuckle

Thank you Justin. I got it to work earlier but will implement this
string builder for efficiency. Once again you come through in the
clutch. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,117
Latest member
Matilda564
Top