OutOfBoundsException on WebListBox2017

Sure :slight_smile: I tend to go for the “give enough information for someone to discover the solution” approach, but am always happy to help if more is needed.

What’s happening is that you’ve defined the Dim ColumnCount, RowCount As Integer variables, but they are both 0. Since they are zero, the loops only iterate once.

Here’s how I would refactor and prettify this method:

Public Sub ExportAsCSV(extends lb as WebListbox, fTarget as FolderItem)
  // Because asking for a FolderItem is not always thread safe
  // I've designed this method to accept an already constructed FolderItem
  
  // This function also assumes you asked the user if they want to overrwite 
  // the file because it will overwrite exsiting files (generally the save dialog does this)
  
  // This is where the rows will be stored
  dim arsRows() as String
  
  dim iColMax as Integer = lb.ColumnCount - 1
  dim iRowMax as Integer = lb.RowCount - 1
  
  // Iterate the rows and columns of the listbox
  for iRow as Integer = 0 to iRowMax
    dim arsThisRow() as String
    
    for iCol as Integer = 0 to iColMax
      // Include the quotes inside the field
      arsThisRow.Append(chr(34) + lb.Cell(iRow, iCol) + chr(34))
      
    next iCol
    
    // Add this row to all our rows
    arsRows.Append(Join(arsThisRow, ","))
    
  next iRow
  
  // All rows are now ready
  dim sRowsOut as String = Join(arsRows, EndOfLine.UNIX)
  
  // Create the file (overwriting what that may exist)
  dim tos as TextOutputStream = TextOutputStream.Create(fTarget)
  
  // Write it all out
  tos.Write(sRowsOut)
  tos.Close
  
End Sub

I refactored a little as well. Acquiring a FolderItem isn’t always thread safe, so to make this function thread safe it expects you pass it a FolderItem. This makes the code a little more transportable between projects (and other forum readers!)

You would use my version like this

// Get the FolderItem
dim fDestination as FolderItem = SpecialFolder.Documents.child("test.csv")

// Write to CSV
MyWebListbox1.ExportAsCSV(fDestination)

Hopefully this helps. Let us know if you have more questions. Happy coding!

4 Likes