SilverShotBee SilverShotBee - 3 months ago 63
Vb.net Question

VB.Net passing datagridview row from one form to another form that is already open

I'm trying to develop a search window that allows a user to fill in criteria, then click the search button. When the search button is clicked the results are returned in a

DataGridView
. When a result in the
DataGridView
is clicked, I'd like to pass the row number to another form that is already open.

I understand I can pass the result by creating a new instance of the form. I pass variables to my Search Window using the following method:

Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click

Dim ST = New Search_Tool(DGV_Ongoing.DataSource, AgencyOptions, EthnicityOptions, EmploymentTypeOptions, EmploymentStatusOptions,
CategoryOptions, OutcomeOptions)

ST.Show()

End Sub


however I cannot call the form I want to pass the row value to because it is already open (its the main form). Is there a way to handle this? I'm struggling to find any information that doesn't call the form to open it whilst passing the data.

I can't reference
Main_form.Main_DGV.CurrentCell
as Visual Studio says it requires an Object Reference in order to do so.

Thanks in advance!

Answer

I'd recommend an event in your Search_Tool form that is raised when the user has found what they're looking for.

The main form is subscribed to that and can then access its datagrid.

Class Search_Tool
    Inherits Form

    Public Event SearchResultFound(resultId As Integer)

    Private Sub OnUserClickedARowOrPressedAButtonOrWhatever()
        RaiseEvent SearchResultFound(currentRow.Id)
    End Sub

End Class

And in the main form.

Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click

    Dim ST = New Search_Tool(DGV_Ongoing.DataSource, AgencyOptions, EthnicityOptions, EmploymentTypeOptions, EmploymentStatusOptions,
                                     CategoryOptions, OutcomeOptions)
    AddHandler ST.SearchResultFound, Sub(result As Integer)
                                         'handle your result id here.
                                         MessageBox.Show("User selected row " & result)
                                     End Sub
    ST.Show()

End Sub

The advantage of this is that the SearchForm doesn't need to know what it's being used by. It's just there to give results which will make it easier to reuse later.

Comments