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.



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)

        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")

        dataGridView1.DataSource = coursesTable



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.

Edited 1 Year Ago by cgeier

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)}

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

This article has been dead for over six months. Start a new discussion instead.