 |

12-15-2009, 06:53 PM
|
|
Regular
|
|
Join Date: Dec 2009
Posts: 54
|
|
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
|
|

12-15-2009, 09:39 PM
|
 |
Centurion
|
|
Join Date: May 2008
Location: Denver, CO USA
Posts: 190
|
|
|
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.
|
|

12-15-2009, 09:46 PM
|
|
Regular
|
|
Join Date: Dec 2009
Posts: 54
|
|
Quote:
Originally Posted by hawkvalley1
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!
|
|

12-15-2009, 10:17 PM
|
 |
Fabulous Florist
Forum Leader * Guru *
|
|
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,416
|
|
The way I do this in my projects is as follows: - Write a class to represent one line of data from the file.
- Write a class that can read the file and output an array of the class from 1.
- 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.
|
|

12-15-2009, 10:23 PM
|
|
Regular
|
|
Join Date: Dec 2009
Posts: 54
|
|
Quote:
Originally Posted by AtmaWeapon
The way I do this in my projects is as follows: - Write a class to represent one line of data from the file.
- Write a class that can read the file and output an array of the class from 1.
- 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
|
|

12-16-2009, 08:49 AM
|
 |
Fabulous Florist
Forum Leader * Guru *
|
|
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,416
|
|
|
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.
|
|

12-17-2009, 12:16 AM
|
|
Regular
|
|
Join Date: Dec 2009
Posts: 54
|
|
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
|
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
|
|
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|
|