Hi guys,

I want to know how you pass a selected row value from one DatagridView to another Datagridview.

Example : DatagridView 1 shows the students list. when one student record(row) is doubleclicked a new window opens with another datagridview where it shows the courses the student is attending to.

Thankyou

Hi

Not knowing how your database is setup the following is just a pointer.

If your first DataGridView that lists the students has a StudentID (let's say this is the first column in the DataGridView) then you could pass this to your second form. In your second form, declare the following property:

    Public Property studentId As Integer

And then when you double click your DataGridView on the first form you can pass this to the property using:

    Private Sub DataGridView1_DoubleClick(sender As Object, e As EventArgs) Handles DataGridView1.DoubleClick

        If DataGridView1.SelectedRows.Count > 0 Then

            Dim newForm As New Form2
            newForm.studentId = Convert.ToInt32(DataGridView1.SelectedRows(0).Cells(0).Value.ToString)
            newForm.Show()

        End If

    End Sub

Now that you have the StudentID available to you on your second form, you can use the Form_Load event to query your database for all courses that relate to that StudentID. Something like the following if this were an Access database:

        Dim connectionString As String = "Your connection string"
        Dim adapter As New OleDbDataAdapter("SELECT * FROM Courses WHERE StudentID=?", connectionString)

        adapter.SelectCommand.Parameters.AddWithValue("?", studentId)

        Dim coursesTable As New DataTable("Courses")
        adapter.Fill(coursesTable)

        dataGridView1.DataSource = coursesTable

        adapter.Dispose()

HTH

If you're creating a new "child" form each time, it isn't necessary to use a property, data can be passed using a constructor.

Public Class Form2

    Private _studentId As Integer

    Public Sub New(ByVal studentId As Integer)
        _studentId = studentId
    End Sub

End Class

Use a property if you are creating the "child" form and need to update the data after the form has already been created.

Or to have the best of both, initialise the property when constructing Form 2:

            Dim newForm As New Form2 With {.studentId = Convert.ToInt32(DataGridView1.SelectedRows(0).Cells(0).Value.ToString)}
            newForm.Show()

Both methods are valid, as with most things, more than one way to skin a cat.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.