我有一个包含大量文本框的应用程序,基本上是要填写的表格。一个标签控件中有几个标签页。在保存数据时,我只需遍历文本框,获取它们的名称和文本,然后将其放入带有“|”的文本文件中 作为分隔符。这很好用,我可以看到我所有的文本框和文本文件中的数据。现在问题来了。当我读回文件(将保存的数据加载回表单)时,它会遍历控件名称并将文本更改为文件中的任何内容。它适用于表单上的文本框,但是当它到达标签页上的第一个文本框时会失败。我该如何解决?如果有更好的方法来保存数据,我会全力以赴。
这是写入文件的代码:
Private Sub savefile(file As String)
Dim ctl As Control = Me
Dim sw As System.IO.StreamWriter
sw = My.Computer.FileSystem.OpenTextFileWriter(file, False)
Do
ctl = Me.GetNextControl(ctl, True)
If ctl IsNot Nothing Then
If TypeOf ctl Is TextBox Then
sw.WriteLine(ctl.Name.ToString.Substring(3) & "|" & ctl.Text)
End If
End If
Loop Until ctl Is Nothing
sw.Close()
End Sub
这是读取文件并更新文本框的代码:
Private Sub ReadFile(filename)
Dim strfilename As String = filename
Dim num_rows, x, y As Integer
Dim strarray(1, 1) As String
Dim ctrl As Control = Me
'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strrecords() As String
Dim strfields() As String
'Load content of file to strLines array
strrecords = tmpstream.ReadToEnd().Split(vbCrLf)
' Redimension the array.
num_rows = UBound(strrecords)
ReDim strarray(num_rows, 2)
' Copy the data into the array.
For x = 0 To num_rows - 1
strfields = strrecords(x).Split("|")
For y = 0 To 1
strarray(x, y) = strfields(y)
Next
Next
' Display the data in listbox
For x = 0 To num_rows - 1
Dim tbxname As String = strarray(x, 0)
tbxname = Remove(tbxname) 'routine that removes invisible characters
tbxname = "tbx" & tbxname
MsgBox(tbxname) 'used to verify each file and which one fails
Me.Controls(tbxname).Text = strarray(x, 1)
Next
Else : MsgBox("File doesn't exist!")
End If
End Sub
我希望这是足够的信息。提前感谢您的帮助!!