以下代码允许我保存文本框&组合框数据到文件....
\w*
哪个有用但我有11个表格(t3frm到t13frm)。 有没有办法将此代码放在循环中而不是重复代码11次? 感谢。
答案 0 :(得分:0)
如果您将此表单作为参数传入,则不必重复此代码:
Public Class SomeSharedClass
Public Sub DoWork(ByVal frmTarget As Form)
sw = New StreamWriter(fname, False)
For i As Integer = 1 To 9
Dim tb = DirectCast(frmTarget.Controls("TextBoxLo" & i), TextBox)
Dim cb = DirectCast(frmTarget.Controls("comboboxlo" & i), ComboBox)
sw.WriteLine(tb.Text)
sw.WriteLine(Val(cb.SelectedIndex))
Next
For i As Integer = 1 To 3
Dim tb = DirectCast(frmTarget.Controls("textboxhi" & i), TextBox)
Dim cb = DirectCast(frmTarget.Controls("comboboxhi" & i), ComboBox)
sw.WriteLine(tb.Text)
sw.WriteLine(Val(cb.selectedindex))
Next
sw.Close()
'Me.Close()
'frmTarget.Close()?
End Sub
End Class
然后从表格中调用它:
Dim objSharedClass As New SomeSharedClass()
objSharedClass.DoWork(Me)
或者如果您在某个地方,您可以访问所有希望运行它的表格:
objSharedClass.DoWork(t3frm)
objSharedClass.DoWork(t4frm)
objSharedClass.DoWork(t5frm)
'Etc
如果你需要单个StreamWriter中的所有内容,你也可以传递它:
Public Function DoWork(ByVal frmTarget As Form, ByVal sw As StreamWriter) As StreamWriter
'Don't initialize or close the StreamWriter here anymore! Do the other code though.
Return sw
End Function
然后用法:
sw = New StreamWriter(fname, False)
sw = objSharedClass.DoWork(t3frm, sw)
sw = objSharedClass.DoWork(t4frm, sw)
'etc
sw.Close()