Results 1 to 3 of 3

Thread: Writing to files, adding to collections

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2013
    Posts
    14

    Writing to files, adding to collections

    Hi,

    I have been having issues with my application. Basically, I am reading a file, saving it into a collection. Then, modifying the collection, and having the option to save the changes back into the file.

    I chose to open the file at form load, read each line and save each into the collection's property, and have the collection key value displayed in the list box. I can then, select the key value, and have each collection property displayed in labels on the form. Also, I am to either add new items, or update existing ones. I am currently having trouble, displaying the items (stored in the collection properties) added, but also previously there, when I select their key value from the list box. I have an inventory number serving as a key, and a description, a cost price, a retail price, and onhand counts displayed in labels. Every time that I select an item from the list box I get the following error:

    argument 'index' is not a valid value
    I have trouble figuring out what is going on.

    I have:
    a separate collection declaration, a separate class declaration with inventory properties.

    a main form displaying the list box, with labels, and also buttons to either display, add, or update the collection. With of course, the option, to save data back into the file.
    Code:
    Imports System.IO
    
    Public Class frmMain
    
        Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim objInventory As New Inventory
            Dim inventoryFile As StreamReader
    
            Try
                'Open the file.
                inventoryFile = File.OpenText("Inventory.txt")
    
                'Enter loop and read till end of file.
                Do Until inventoryFile.Peek = -1
    
                    'Read lines from file, save into Inventory object properties.
                    objInventory.InvNumber = inventoryFile.ReadLine
                    objInventory.Description = inventoryFile.ReadLine
                    objInventory.Cost = inventoryFile.ReadLine
                    objInventory.Retail = inventoryFile.ReadLine
                    objInventory.OnHand = inventoryFile.ReadLine
    
                    'Display inventory number in list box.
                    lstInventory.Items.Add(objInventory.InvNumber)
                Loop
    
                'Close the file.
                inventoryFile.Close()
            Catch
                'Display error message.
                MessageBox.Show("The file cannot be opened")
            End Try
        End Sub
     
    
        Private Sub lstInventory_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstInventory.SelectedIndexChanged
         
        End Sub
    
        Private Sub mnuFileExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileExit.Click
            'Close the form.
            Me.Close()
        End Sub
        Private Sub btnAddInventory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddInventory.Click
            'Create an instance of the frmAdd form.
            Dim addForm As New frmAdd
    
            'Display the form.
            addForm.ShowDialog()
        End Sub
        Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
            'Create an Inventory object
            'Create an Inventory object
            Dim objInventory As Inventory
    
            'Determine if item is selected.
            If lstInventory.SelectedIndex <> -1 Then
    
                'Retrieve student's data from inventoryCollection. Convert object into Inventory object.
                Try
    
                    objInventory = CType(inventoryCollection.Item(lstInventory.SelectedItem), Inventory)
    
                    'Display data in labels data stored in inventory object.
                    DisplayInput(objInventory)
                Catch ex As Exception
                    'Display error message.
                    MessageBox.Show(ex.Message)
                End Try
            End If
        End Sub
        Private Sub DisplayInput(ByVal objInventory As Inventory)
            Dim sngCost As Single
            Dim sngRetail As Single
    
            lblDisplayInvNum.Text = objInventory.InvNumber.ToString
            lblDisplayDescription.Text = objInventory.Description
            lblDisplayOnHand.Text = objInventory.OnHand.ToString
    
            sngCost = CSng(objInventory.Cost)
            sngRetail = CSng(objInventory.Retail)
    
            lblDisplayCost.Text = sngCost.ToString("c")
            lblDisplayRetail.Text = sngRetail.ToString("c")
        End Sub
    
        Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
            'Create an instance of the frmAdd form.
            Dim updateForm As New frmUpdate
    
            'Display the form.
            updateForm.ShowDialog()
        End Sub
        Private Sub UpdateListBox()
            'Clear the list box
            lstInventory.Items.Clear()
    
            Dim objInventory As Inventory
            For Each objInventory In inventoryCollection
                lstInventory.Items.Add(objInventory.invNumber)
            Next
    
            'Select first item in list
            If lstInventory.Items.Count > 0 Then
                lstInventory.SelectedIndex = 0
            Else
                lblInvNumber.Text = String.Empty
                lblDescription.Text = String.Empty
                lblCost.Text = String.Empty
                lblRetail.Text = String.Empty
                lblOnHand.Text = String.Empty
            End If
        End Sub
    End Class
    I use my add form to load data from my text boxes into my object parameter, display the inventory collection key in my main form list box, and have the option to save data back into the file
    Code:
    Imports System.IO
    
    Public Class frmAdd
        Private Sub frmAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'Set focus.
            txtInvNumber.Focus()
        End Sub
        Private Sub InputData(ByVal objInventory As Inventory)
            'InputData procedures gets data from form and stores it
            'objInventory object parameter.
            objInventory.InvNumber = txtInvNumber.Text
            objInventory.Description = txtDescription.Text
            objInventory.Cost = CSng(txtCost.Text)
            objInventory.Retail = CSng(txtRetail.Text)
            objInventory.OnHand = CInt(txtOnHand.Text)
        End Sub
    
        Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
            'Close the form.
            Me.Close()
        End Sub
    
        Private Sub btnAddtoForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddtoForm.Click
            'Create instance of Inventory class.
            Dim newInventory As New Inventory
    
            'Get input data from form.
            InputData(newInventory)
    
            'Display inventory number.
            frmMain.lstInventory.Items.Add(newInventory.InvNumber)
    
            'Save inventory object to inventoryCollection.
            AddRecord(newInventory)
    
            'Check for check box selection.
            If chkSaveCollection.Checked = True Then
                Dim writeFile As StreamWriter
                Dim sngCost As Single
                Dim sngRetail As Single
    
                sngCost = CSng(newInventory.Cost)
                sngRetail = CSng(newInventory.Retail)
    
                Try
                    'Open the file in Append mode.
                    writeFile = File.AppendText("Inventory.txt")
    
                    'Write to file.
                    writeFile.WriteLine(newInventory.InvNumber)
                    writeFile.WriteLine(newInventory.Description)
                    writeFile.WriteLine(newInventory.Cost)
                    writeFile.WriteLine(newInventory.Retail)
                    writeFile.WriteLine(newInventory.OnHand)
    
                    'Close StreamWriter.
                    writeFile.Close()
                Catch ex As Exception
                    'Display error message
                    MessageBox.Show(ex.Message)
                End Try
            End If
            'Return focus.
            txtInvNumber.Focus()
        End Sub
    End Class

    Can anyone help?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Writing to files, adding to collections

    You're not actually keeping any of the data you read except the inventory number. Here's what you should do:

    1. Create a BindingList(Of Inventory).
    2. As you read the file, create a New Inventory object each iteration of the loop, set its properties and then Add it to the list.
    3. Bind the list to the ListBox by setting the DisplayMember, ValueMember and DataSource of the ListBox.
    4. Bind the list to the Labels as well so that they update automatically when the user makes a selection.
    5. To get the current item, use the SelectedItem property of the ListBox.
    6. When you update an existing item, call the ResetItem method of the BindingList and use the SelectedIndex of the ListBox as the position.
    7. When you add a new item, call the ResetBindings method of the BindingList.

    I would also strongly recommend not storing one record on multiple lines. I'd recommend one record per record and delimiting use commas or Tabs or something else if you have a good reason for it.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    New Member
    Join Date
    Feb 2013
    Posts
    14

    Re: Writing to files, adding to collections

    Quote Originally Posted by jmcilhinney View Post
    You're not actually keeping any of the data you read except the inventory number. Here's what you should do:

    1. Create a BindingList(Of Inventory).
    2. As you read the file, create a New Inventory object each iteration of the loop, set its properties and then Add it to the list.
    3. Bind the list to the ListBox by setting the DisplayMember, ValueMember and DataSource of the ListBox.
    4. Bind the list to the Labels as well so that they update automatically when the user makes a selection.
    5. To get the current item, use the SelectedItem property of the ListBox.
    6. When you update an existing item, call the ResetItem method of the BindingList and use the SelectedIndex of the ListBox as the position.
    7. When you add a new item, call the ResetBindings method of the BindingList.

    I would also strongly recommend not storing one record on multiple lines. I'd recommend one record per record and delimiting use commas or Tabs or something else if you have a good reason for it.
    Am I basically creating a dataset and using the file as a data source?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width