我正在練習VB.NET,並且在閱讀和寫入.dat文件時遇到了問題。我已經建立了一個臨時存儲數據的結構(見下文)。如何將格式化數據寫入文件然後讀取它? VB.NET(2012年版)
Structure CustomerType
Dim AccountNum As String
Dim Surname As String
Dim Forename As String
Dim Balance As Decimal
End Structure
然後我昏暗的一切。
Dim Customers(9) As CustomerType
Dim Filename As String = "Accounts.dat"
Dim NumberOfRecords As Short = 0
Dim myFormat As String = "{0,-15}|{1,-15}|{2,-10}|{3,-10}"
我有一個按鈕,創建一個新的帳戶,這是我得到的問題。
FileOpen(1, Filename, OpenMode.Random, , ,)
For i = 1 To Customers.Length() - 1
With Customers(i)
.Forename = InputBox("First name", "Forename")
Do Until .Forename <> "" And TypeOf .Forename Is String
.Forename = InputBox("First name", "Forename")
Loop
.Surname = InputBox("Surname", "Surname")
Do Until .Surname <> "" And TypeOf .Surname Is String
.Surname = InputBox("Surname", "Surname")
Loop
.AccountNum = InputBox("Account Number of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Account Number")
Do Until .AccountNum.Length = 8 And TypeOf .AccountNum Is String
.AccountNum = InputBox("Account Number of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Account Number")
Loop
.Balance = InputBox("Balance of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Balance")
Do Until .Balance > -1
.Balance = InputBox("Balance of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Balance")
Loop
FilePut(1, Customers, NumberOfRecords + 1)
NumberOfRecords += 1
lblNumberOfRecords.Text = NumberOfRecords
End With
Next
FileClose(1)
我有另一個按鈕,顯示列表框中的數據。我只能得到一個項目才能顯示錯誤長度錯誤。
Dim Index As Integer
ListBox1.Items.Clear()
ListBox1.Items.Add(String.Format(myFormat, "Forename", "Surname", "Acc. Num.", "Balance"))
ListBox1.Items.Add("_____________________________________________________")
FileOpen(1, Filename, OpenMode.Random, , ,)
For Index = 1 To NumberOfRecords
FileGet(1, Customers)
ListBox1.Items.Add(String.Format(myFormat, Customers(Index).Forename, Customers(Index).Surname, Customers(Index).AccountNum, Format(Customers(Index).Balance, "currency")))
Next Index
FileClose(1)
我的主要問題是我做錯了什麼,我該如何解決?
許多在此先感謝, 喬丹
您是否考慮過使用[serialization](http://msdn.microsoft.com/zh-cn/library/ms973893.aspx)? –
我忘了說我也在學習過程中。你能否給我一小段代碼,以便我能理解正在發生的事情。 MSDN是有幫助的,但並沒有真正解釋它到我能理解的地步:) – Rinslep
@Bjørn-RogerKringsjå的例子很棒。我同意這是一個更好的方法,因爲你在.NET中。 –