Question

As a learning development, I am developing a Pizza Calc Program that is meant to save to a text file when the user is done selecting their pizza. I am attempting to save the lines from the listbox into the text file in the designated file in the H:\ Drive (weird.... I know)... This is the main form:

enter image description here

On the 'Complete Transaction' Button Press, it shows a dialog:

enter image description here

On the OK Button Press: (This code is in Dialog1.vb)

Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        MsgBox("Your final Price is " & frmPizzas.txtFinalAmount.Text)
        saveFile("H:\pizza_receipt.txt")
        Application.Exit()
End Sub
Sub saveFile(ByVal filePath As String)
    Try
        Dim writeFile As IO.StreamWriter
        writeFile = File.CreateText(filePath)
        For linesLbo = 0 To frmPizzas.lboTransactionLog.Items.Count
            writeFile.WriteLine(frmPizzas.lboTransactionLog.Items.Item(linesLbo))
        Next
        writeFile.Close()
        MsgBox("The file has been saved successfully!")
    Catch ex As Exception
        'Displays an error log in a Message Box by using the ToString() Arg
        'In order to prevent crashing
        MsgBox(ex.ToString())
    End Try
End Sub

And it catches displaying the MsgBox:

enter image description here

Was it helpful?

Solution

For linesLbo = 0 To frmPizzas.lboTransactionLog.Items.Count

It's been a long while since I've used VB, but I believe Listboxes are 0-based, so you're running one past the end of the item array (for example, if Items.Count is 10, your Items run from 0-9). You would want to do this instead:

For linesLbo = 0 To frmPizzas.lboTransactionLog.Items.Count - 1

OTHER TIPS

For linesLbo = 0 To frmPizzas.lboTransactionLog.Items.Count
            writeFile.WriteLine(frmPizzas.lboTransactionLog.Items.Item(linesLbo))

I may be wrong, as I don't use the mongrel language (god tier C# here), but you're indexing into an array from 0 to 7 (frmPizzas.lboTransactionLog.Items.Count is the total number of items in the array), however the array's maximum index is 6 (0,1,2,3,4,5,6 == seven numbers)

Try

For linesLbo = 0 To frmPizzas.lboTransactionLog.Items.Count - 1

In C# I'd just

foreach var line in frmPizzas.lboTransactionLog.Items
    //writeline here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top