您可以傳遞對控件的引用以用於搜索文本。這使得您的SearchFields方法更通用。作爲一個例子,我創建了一個名爲frmNew
的表單和一個名爲Searching
的模塊。在窗體上,我放置了一個名爲Ok
的按鈕,一個TextBox和一個ComboBox。
Public Class frmNew
Private Sub Ok_Click(sender As Object, e As EventArgs) Handles Ok.Click
Searching.SearchFields(TextBox1)
Searching.SearchFields(ComboBox1)
Me.Close()
End Sub
End Class
有兩種方法,你可以去處理傳遞給模塊的控制(我命名爲Searching
)。首先,你可以檢查控件的類型,並基於該採取行動:
Module Searching
Sub SearchFields(textSource As Control)
Dim str As String = ""
' just for invesigating, show the type of the control.
Console.WriteLine(TypeName(textSource))
If TypeOf textSource Is System.Windows.Forms.TextBox Then
str = textSource.Text
ElseIf TypeOf textSource Is System.Windows.Forms.ComboBox Then
Dim src = DirectCast(textSource, ComboBox)
If src.SelectedIndex >= 0 Then
str = src.SelectedItem.ToString()
Else
' nothing was selected. Do whatever is appropriate.
str = "NOTHING SELECTED!"
End If
End If
'TODO: the searching code.
Console.WriteLine(str)
End Sub
End Module
或者,你可以採取的方法重載,它運行的對應參數的方法版本的優勢(S)你通過它:
Module Searching
Sub SearchFields(src As TextBox)
DoSearch(src.Text)
End Sub
Sub SearchFields(src As ComboBox)
'TODO: check an item is selected.
Dim txt = src.SelectedItem.ToString()
DoSearch(txt)
End Sub
Private Sub DoSearch(s As String)
' do the search
Console.WriteLine(s)
End Sub
End Module
請先提供一些代碼。 – Neolisk
已添加評論 – user3180163
'Dim frm As New frmNew' does not refer the existing form。您必須將參考作爲參數傳遞。轉移到.Net將需要您重新考慮您的程序的結構。一般來說,模塊應該替換爲類。絕大多數情況下避免使用全局變量。 – LarsTech