Hey Guys! ,
Im having a bit of a problem here. I need to add a certain string in this case (') infront of every item in my listbox.

So lets say items are :
item1
item2
item3
item4

After i execute a code i want it to be
item1'
item2'
item3'
item4'

It would be highly appreciated if someone could help me out here!. Thanks alot

Dani AI

Generated

There’s a mismatch between the text “in front” and the example (which appends an apostrophe). Either way, the exact fix depends on whether this is an ASP.NET WebForms ListBox (Items are ListItem objects and can be edited in-place) or a WinForms ListBox (Items are usually strings and require replacing). pointed out adding the quote when inserting items; showed changing existing items in-place. For ASP.NET WebForms a safe, simple approach is to update each ListItem.Text directly:

For Each li As System.Web.UI.WebControls.ListItem In ListBox1.Items
    li.Text = "'" & li.Text    ' prepend an apostrophe; swap operands to append
Next

Troubleshooting notes based on what can cause “it doesn’t work” symptoms:

  • If the ListBox is data-bound, modify the data source before calling DataBind or adjust the ListItem.Text after DataBind. Re-binding on every postback will undo changes — bind only inside If Not IsPostBack Then ... End If.
  • If you used a For Each over strings (WinForms), assigning to the loop variable won’t change the collection. Use an index-based loop or build a temporary list and replace the Items collection afterwards.
  • Put a breakpoint and inspect ListBox1.Items.Count and the actual item values before and after running the code to confirm your modification runs at the right time.

Preferred patterns: change the source (if possible) before binding, or update ListItem.Text after binding for WebForms. If the apostrophes are later used in SQL, use parameterized queries rather than string concatenation to avoid SQL issues.

Recommended Answers

All 3 Replies

Just hardcoded the data with single quotes

lstView.Items.Add("CSharp'");
        lstView.Items.Add("Vb'");

Or
U can get data from backend and using the loop jus concate the backend data with "'" and add into listbox.

Hey when i do that it doesnt work. All it does is that it adds to items ( csharp' and vb')

thanks

If your listbox already contains items then this should work:

For i As Integer = 0 To lstBox.Items.Count - 1
   lstBox.Items(i) = lstBox.Items(i) & "'"
Next

Or if you need to add ' while adding items then this is the way to go:

lstBox.Items.Add(<some source> & "'")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.