Form2 以 **模態對話框** (`ShowDialog`) 顯示,使用者選取後設定公共屬性,Form1 讀取屬性回填 TextBox。
Public Class Form2
' 對外暴露選取結果
Public Property SelectedValue As String = ""
Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
If e.RowIndex >= 0 Then
SelectedValue = DataGridView1.Rows(e.RowIndex).Cells(1).Value?.ToString() ' 第 2 欄
Me.DialogResult = DialogResult.OK ' 關鍵:設定 DialogResult 關閉視窗
End If
End Sub
End Class
Public Class Form1
Private Sub TextBox1_DoubleClick(sender As Object, e As EventArgs) Handles TextBox1.DoubleClick
Using frm As New Form2()
' 這裡可預先載入 Form2 的 DataGridView 資料
' frm.LoadData()
If frm.ShowDialog(Me) = DialogResult.OK Then
TextBox1.Text = frm.SelectedValue
End If
End Using ' 自動 Dispose
End Sub
End Class
' Form2
Public Event ValueSelected(value As String)
Private Sub DataGridView1_CellDoubleClick(...) Handles ...
RaiseEvent ValueSelected(DataGridView1.Rows(e.RowIndex).Cells(1).Value.ToString())
Me.Close()
End Sub
' Form1
Private Sub TextBox1_DoubleClick(...) Handles ...
Dim frm As New Form2()
AddHandler frm.ValueSelected, AddressOf OnValueSelected
frm.ShowDialog()
End Sub
Private Sub OnValueSelected(value As String)
TextBox1.Text = value
End Sub
事件模式適合**多處呼叫 Form2** 或**不想暴露公共屬性**的情況。