在表2中,我有一个datagridview,其中填充了数据库的搜索结果。
我的目标是,当单击datagridview中的一个单元格时,它将通过将单击的行的索引和记录集传递给表单1的代码中的函数来填充表单1上文本框的内容。
在表格1中,我有以下内容:
rs = New ADODB.Recordset
rs .CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs.Open("Exec " & class_Stored_Procedures.cs_spMyO_KontaktPersonen_SEA$ & " " & SQL$, gConnectionString$, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockOptimistic)
Dim f = New ChildForm()
f.Show()
f.Focus()
f.getAdoRecords(rs)
'
'This is the part in question
AddHandler f.DataGridView1_CellClick, FillForm1(rs, (index of the row clicked))
然后...
Private Function FillForm1(rs As ADODB.RecordSet, i As Integer)
'fill textboxes with record i values of the recordset
End Function
在表格2
答案 0 :(得分:1)
使用自定义数据引发事件的最简单方法是声明并引发自定义事件。可以在您的DataGridView
的 _CellClick 事件处理程序中触发此新事件。通过这种方式与DataGridView分离,将有助于隔离和隔离任何将来的更改。
SelectedValueEventArgs类 创建此类,以保存要传递给“父”表单的事件信息,例如, Form1
Public Class SelectedValueEventArgs
Inherits EventArgs
Public Sub New(rs As ADODB.RecordSet, i As Integer)
RecordSet = rs
Index = i
End Sub
Public Property RecordSet As ADODB.RecordSet
Public Property Index As Integer
End Class
声明SelectedValueChanged事件
使用适当的名称声明要引发的事件。我去了SelectedValueChanged。此事件应在您的 Form2 类
中声明Public Event SelectedValueChanged As EventHandler(Of SelectedValueEventArgs)
引发事件
在DataGridView的_CellClick事件处理程序中,设置事件Args并引发新事件
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim rs As ADODB.RecordSet = ' Set your ADOBB.RecordSet here
Dim i As Integer = e.RowIndex
Dim eventArgs As New SelectedValueEventArgs(rs, i)
OnSelectedValueChanged(eventArgs)
End Sub
' This function will do the hard work of raising the event to parent forms
Protected Overridable Sub OnSelectedValueChanged(e As SelectedValueEventArgs)
RaiseEvent SelectedValueChanged(Me, e)
End Sub
在家长表格中处理事件
最后,在您的父表单(Form1)中,当您显示 Form2 时,为新创建/发布的事件添加一个处理程序,然后在事件处理程序( form2_SelectedValueChanged )
Private Sub btnButton1_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim f As New Form2
AddHandler f.SelectedValueChanged, AddressOf form2_SelectedValueChanged
f.Show()
End Sub
Private Sub form2_SelectedValueChanged(sender As Object, e As SelectedValueEventArgs)
Debug.Print(e.Index)
End Sub