Go Back  Xtreme Visual Basic Talk > Visual Basic .NET (2002/2003/2005/2008, including Express editions) > .NET General > Changing data in text file or array?


Reply
 
Thread Tools Display Modes
  #1  
Old 12-15-2009, 06:53 PM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Exclamation Changing data in text file or array?


I have a csv text file, shown below that I want to edit based on user inputs. When the user wants to change the current price of a stock, they enter the stock name, and the new price. When the button is clicked, VB needs to find the appropriate stock, and then change the current price.

The data needs to be pulled from the text file into a temporary file, changed, then the temp file needs to be renamed to the original file name and the original file deleted.

This is the only part of the program I can not figure out. I have put my program code here as well. The click event that I need this to work on is: Private Sub btnUpdateStock_Click --- I have been playing with code in that section, so that's why there si abunch of crazey code there.

TEXT FILE
Code:
Amgen,200,8/19/97,12.625,47.42
Delta Airlines,100,12/3/97,55.875,15.19
Novell,500,8/27/97,10.375,6.13
PPG,100,12/18/97,28.375,62.64
Timken,300,3/13/98,34.625,26.88
CODE:

Code:
Public Class frmStockAnalysis
   
    ' Declare variables
    Dim stockData() As String
    Dim stockName As String
    Dim numShares As Integer
    Dim datePurchased As String
    Dim cost As Double
    Dim currentValue As Double
    Dim profit_loss As Double
    Dim fmtStr As String = "{0,-15}{1,25:C}{2,25:C}{3,25:C}"
    Dim fmtStr2 As String = "{0,-15}{1,25}{2,25}{3,25:N3}{4,25:N2}"

    Private Sub btnQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuit.Click
        Close()
    End Sub

    Private Sub btnProfitLoss_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProfitLoss.Click
        ' Clear List Box contents
        lstResults.Items.Clear()

        ' Open csvSTOCKS.TXT file
        Dim sr As IO.StreamReader = IO.File.OpenText("csvSTOCKS.TXT")

        ' Listbox headings
        lstResults.Items.Add(String.Format(fmtStr, "", "", "Current", "Profit"))
        lstResults.Items.Add(String.Format(fmtStr, "Stock", "Cost", "Value", "(or Loss)"))
        lstResults.Items.Add(String.Format(fmtStr, "===============", "===============", "===============", "==============="))

        ' Retrieve data from file
        Do While (sr.Peek <> -1)
            stockData = sr.ReadLine.Split(","c)
            stockName = stockData(0)
            numShares = CInt(stockData(1))
            cost = CDbl(stockData(3) * numShares)
            currentValue = CDbl(stockData(4) * numShares)

            ' Calculate Profit/Loss
            profit_loss = currentValue - cost

            ' Format and output data from file into listbox
            lstResults.Items.Add(String.Format(fmtStr, stockName, cost, currentValue, profit_loss))
        Loop

        ' Close file reader
        sr.Close()

    End Sub

    Private Sub btnDisplayStocks_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayStocks.Click
        ' Clear List Box contents
        lstResults.Items.Clear()

        ' Open csvSTOCKS.TXT file
        Dim sr As IO.StreamReader = IO.File.OpenText("csvSTOCKS.TXT")

        ' Listbox headings
        lstResults.Items.Add(String.Format(fmtStr2, "", "Number", "Date", "Purchase", "Current"))
        lstResults.Items.Add(String.Format(fmtStr2, "Stock", "of Shares", "Purchased", "Price/Share", "Price/Share"))
        lstResults.Items.Add(String.Format(fmtStr2, "_______________", "_________________________", "_________________________", _
                                           "_________________________", "_________________________"))
        lstResults.Items.Add("")

        ' Retrieve data from file
        Do While (sr.Peek <> -1)
            stockData = sr.ReadLine.Split(","c)
            stockName = stockData(0)
            numShares = CInt(stockData(1))
            datePurchased = (stockData(2))
            cost = CDbl(stockData(3))
            currentValue = CDbl(stockData(4))

            ' Format and output data from file into listbox
            lstResults.Items.Add(String.Format(fmtStr2, stockName, numShares, datePurchased, cost, currentValue))
        Loop

        ' Close file reader
        sr.Close()

    End Sub

    Private Sub btnUpdateStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdateStock.Click
        ' Clear List Box contents
        lstResults.Items.Clear()

        Dim output() As String = {tbxStock.Text, tbxNumShares.Text, tbxDatePurch.Text, tbxPurchPrice.Text, tbxPrice.Text}

        ' Check to see that the appropriate input exists
        If (tbxStock.Text <> "") And (tbxPrice.Text <> "") Then

            ' Open csvSTOCKS.TXT file
            Dim sr As IO.StreamReader = IO.File.OpenText("csvSTOCKS.TXT")

            Do While (sr.Peek <> -1)
                stockData = sr.ReadLine.Split(","c)
                stockName = stockData(0)
                numShares = CInt(stockData(1))
                cost = CDbl(stockData(3) * numShares)
                currentValue = CDbl(stockData(4) * numShares)

            Loop




            ' Open csvSTOCKS.TXT file, and write new stock information to file
            Dim sw As IO.StreamWriter = IO.File.AppendText("csvSTOCKS.TXT")
            sw.WriteLine((Join(output, ",")))

            ' Close file reader
            sr.Close()
            sw.Close()

            ' Clear text boxes
            tbxStock.Clear()
            tbxPrice.Clear()

            ' Show success message
            MessageBox.Show("Stock information successfully updated.", "Update Complete!")
        Else
            MessageBox.Show("Please be sure 'Stock' and 'Current Price'  fields are completed.", "Update Failed!")

        End If
    End Sub

    Private Sub btnAddStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddStock.Click
        ' Clear List Box contents
        lstResults.Items.Clear()

        Dim output() As String = {tbxStock.Text, tbxNumShares.Text, tbxDatePurch.Text, tbxPurchPrice.Text, tbxPrice.Text}

        ' Check to see that the appropriate input exists
        If (tbxStock.Text <> "") And (tbxPrice.Text <> "") And (tbxDatePurch.Text <> "") And (tbxNumShares.Text <> "") _
                And (tbxPurchPrice.Text <> "") Then

            ' Open csvSTOCKS.TXT file, and write new stock information to file
            Dim sw As IO.StreamWriter = IO.File.AppendText("csvSTOCKS.TXT")
            sw.WriteLine((Join(output, ",")))

            ' Close file reader
            sw.Close()

            ' Clear text boxes
            tbxStock.Clear()
            tbxNumShares.Clear()
            tbxDatePurch.Clear()
            tbxPurchPrice.Clear()
            tbxPrice.Clear()

            ' Show success message
            MessageBox.Show("Stock information successfully added.", "Success!")
        Else
            MessageBox.Show("Please be sure all fields are completed.", "Add Failed!")

        End If
    End Sub

    Private Sub frmStockAnalysis_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class
Reply With Quote
  #2  
Old 12-15-2009, 09:39 PM
hawkvalley1's Avatar
hawkvalley1 hawkvalley1 is offline
Centurion
 
Join Date: May 2008
Location: Denver, CO USA
Posts: 190
Default

That is why I switched to XML files. They are easier to parse for data and changing a single elements data is easy. It wasn't as hard as you think.
Reply With Quote
  #3  
Old 12-15-2009, 09:46 PM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Default

Quote:
Originally Posted by hawkvalley1 View Post
That is why I switched to XML files. They are easier to parse for data and changing a single elements data is easy. It wasn't as hard as you think.
Unfortunately this is the way I have to do it. Anyone have a clue? This is a pain in the butt!
Reply With Quote
  #4  
Old 12-15-2009, 10:17 PM
AtmaWeapon's Avatar
AtmaWeapon AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,416
Default

The way I do this in my projects is as follows:
  1. Write a class to represent one line of data from the file.
  2. Write a class that can read the file and output an array of the class from 1.
  3. Write a class that can take an array of the class from 1 and output it to a file.

Then the application logic is easy. You read the file, manipulate the data in the array, then write the array to the file.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #5  
Old 12-15-2009, 10:23 PM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Default

Quote:
Originally Posted by AtmaWeapon View Post
The way I do this in my projects is as follows:
  1. Write a class to represent one line of data from the file.
  2. Write a class that can read the file and output an array of the class from 1.
  3. Write a class that can take an array of the class from 1 and output it to a file.

Then the application logic is easy. You read the file, manipulate the data in the array, then write the array to the file.
this all has to be done with File I/O, I understand what needs to be done procedurally, but I cant get the code to come together
Reply With Quote
  #6  
Old 12-16-2009, 08:49 AM
AtmaWeapon's Avatar
AtmaWeapon AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,416
Default

I do not understand what is being asked. Your post explains the situation in the first paragraph. The second paragraph states "I need to solve this problem using this particular method." The third paragraph is just a preface to the code, which doesn't follow the method suggested in the second paragraph.

So I suggested, "Hey, the method you outlined in the second paragraph isn't really the best way to do things." and you responded "I know". Verily, the code is actually using something similar to the method I suggested. It creates a string and appends it to the file. You haven't described what is wrong with the code, so I'm not sure what you're looking for.
Reply With Quote
  #7  
Old 12-17-2009, 12:16 AM
CarlMartin10 CarlMartin10 is offline
Regular
 
Join Date: Dec 2009
Posts: 54
Default

I eventually got this to work. For anyone who is interested to see how it was resolved, here is the complete code:

Code:
Public Class frmStockAnalysis
   
    ' Declare variables
    Dim stockData() As String
    Dim stockName As String
    Dim numShares As Integer
    Dim datePurchased As String
    Dim cost As Double
    Dim currentValue As Double
    Dim profit_loss As Double
    Dim fmtStr As String = "{0,-15}{1,25:C}{2,25:C}{3,25:C}"
    Dim fmtStr2 As String = "{0,-15}{1,25}{2,25}{3,25:N3}{4,25:N2}"

    Private Sub btnQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuit.Click
        Close()
    End Sub

    Private Sub btnProfitLoss_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProfitLoss.Click
        ' Clear List Box contents
        lstResults.Items.Clear()

        ' Open csvSTOCKS.TXT file
        Dim sr As IO.StreamReader = IO.File.OpenText("csvSTOCKS.TXT")

        ' Listbox headings
        lstResults.Items.Add(String.Format(fmtStr, "", "", "Current", "Profit"))
        lstResults.Items.Add(String.Format(fmtStr, "Stock", "Cost", "Value", "(or Loss)"))
        lstResults.Items.Add(String.Format(fmtStr, "===============", "===============", "===============", "==============="))

        ' Retrieve data from file
        Do While (sr.Peek <> -1)
            stockData = sr.ReadLine.Split(","c)
            stockName = stockData(0)
            numShares = CInt(stockData(1))
            cost = CDbl(stockData(3) * numShares)
            currentValue = CDbl(stockData(4) * numShares)

            ' Calculate Profit/Loss
            profit_loss = currentValue - cost

            ' Format and output data from file into listbox
            lstResults.Items.Add(String.Format(fmtStr, stockName, cost, currentValue, profit_loss))
        Loop

        ' Close file reader
        sr.Close()

    End Sub

    Private Sub btnDisplayStocks_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayStocks.Click
        ' Clear List Box contents
        lstResults.Items.Clear()

        ' Open csvSTOCKS.TXT file
        Dim sr As IO.StreamReader = IO.File.OpenText("csvSTOCKS.TXT")

        ' Listbox headings
        lstResults.Items.Add(String.Format(fmtStr2, "", "Number", "Date", "Purchase", "Current"))
        lstResults.Items.Add(String.Format(fmtStr2, "Stock", "of Shares", "Purchased", "Price/Share", "Price/Share"))
        lstResults.Items.Add(String.Format(fmtStr2, "_______________", "_________________________", "_________________________", _
                                           "_________________________", "_________________________"))
        lstResults.Items.Add("")

        ' Retrieve data from file
        Do While (sr.Peek <> -1)
            stockData = sr.ReadLine.Split(","c)
            stockName = stockData(0)
            numShares = CInt(stockData(1))
            datePurchased = (stockData(2))
            cost = CDbl(stockData(3))
            currentValue = CDbl(stockData(4))

            ' Format and output data from file into listbox
            lstResults.Items.Add(String.Format(fmtStr2, stockName, numShares, datePurchased, cost, currentValue))
        Loop

        ' Close file reader
        sr.Close()

    End Sub

    Private Sub btnUpdateStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdateStock.Click

        'Declare variables
        Dim stock() As String
        Dim name As String
        Dim changed As Boolean = False
        name = tbxStock.Text.Trim().ToUpper

        ' Check to see that the appropriate input exists
        If (tbxStock.Text <> "") And (tbxPrice.Text <> "") Then

            Dim sr As IO.StreamReader = IO.File.OpenText("csvSTOCKS.TXT")
            Dim sw As IO.StreamWriter = IO.File.CreateText("TEMP.TXT")
            Do While sr.Peek() <> -1
                stock = sr.ReadLine.Split(","c)

                'Update current price
                If name = stock(0).ToUpper Then
                    stock(4) = CStr(CDbl(tbxPrice.Text.Trim()))
                    changed = True
                End If
                sw.WriteLine(Join(stock, ","))
            Loop

            ' Close Reader and Writer
            sr.Close()
            sw.Close()

            ' Delete original file and rename temp file to original file name
            If changed Then
                IO.File.Delete("csvSTOCKS.TXT")
                IO.File.Move("TEMP.TXT", "csvSTOCKS.TXT")
                lstResults.Items.Clear()
            Else
                MessageBox.Show("The stock was not found. Please verify the correct stock is being entered or enter another stock.")
            End If
        End If
    End Sub

    Private Sub btnAddStock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddStock.Click
        ' Clear List Box contents
        lstResults.Items.Clear()

        Dim output() As String = {tbxStock.Text, tbxNumShares.Text, tbxDatePurch.Text, tbxPurchPrice.Text, tbxPrice.Text}

        ' Check to see that the appropriate input exists
        If (tbxStock.Text <> "") And (tbxPrice.Text <> "") And (tbxDatePurch.Text <> "") And (tbxNumShares.Text <> "") _
                And (tbxPurchPrice.Text <> "") Then

            ' Open csvSTOCKS.TXT file, and write new stock information to file
            Dim sw As IO.StreamWriter = IO.File.AppendText("csvSTOCKS.TXT")
            sw.WriteLine((Join(output, ",")))

            ' Close file reader
            sw.Close()

            ' Clear text boxes
            tbxStock.Clear()
            tbxNumShares.Clear()
            tbxDatePurch.Clear()
            tbxPurchPrice.Clear()
            tbxPrice.Clear()

            ' Show success message
            MessageBox.Show("Stock information successfully added.", "Success!")
        Else
            MessageBox.Show("Please be sure all fields are completed.", "Add Failed!")

        End If
    End Sub

    Private Sub frmStockAnalysis_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
 
 
-->