How do you databind a textbox to a column in a related table?

Boruch Tkatch 141 Reputation points
2023-11-06T18:24:46.4033333+00:00

I am trying to learn how to bind a control to a related table and show the corresponding record. In the following example, 2 tables, A and B, each have one column and the 2 columns are related. A DataGridView shows table B, one TextBox shows the corresponding column in B, the other TextBox is meant to show the corresponding column in A, but it just shows the first record in A instead.

Public Class Form1
    Private ReadOnly DataSet As New DataSet

    Private ReadOnly Grid As New DataGridView
    Private ReadOnly B_A As New TextBox With {.Location = New Point(Grid.Location.X, Grid.Location.Y + Grid.Size.Height)}
    Private ReadOnly A_Id As New TextBox With {.Location = New Point(B_A.Location.X + B_A.Size.Width, B_A.Location.Y)}

    Private D As New BindingSource() With {.DataSource = DataSet}

    Private Sub Form1_Load(Sender As Object, Arguments As EventArgs) Handles MyBase.Load
        Setup_DataSet()

        A_Id.DataBindings.Add("Text", D, "A.Id")
        B_A.DataBindings.Add("Text", D, "B.A")

        Grid.DataSource = D
        Grid.DataMember = "B"

        Controls.AddRange({Grid, A_Id, B_A})
    End Sub

    Private Sub Setup_DataSet()
        DataSet.Tables.Add(New DataTable("A"))
        DataSet.Tables.Add(New DataTable("B"))

        DataSet.Tables("A").Columns.Add("Id", GetType(Integer))
        DataSet.Tables("B").Columns.Add("A", GetType(Integer))

        DataSet.Tables("A").Rows.Add(1)
        DataSet.Tables("A").Rows.Add(2)
        DataSet.Tables("A").Rows.Add(3)

        DataSet.Tables("B").Rows.Add(2)
        DataSet.Tables("B").Rows.Add(3)

        DataSet.Tables("A").PrimaryKey = {DataSet.Tables("A").Columns("Id")}
        DataSet.Relations.Add(New DataRelation("B_A", DataSet.Tables("A").Columns("Id"), DataSet.Tables("B").Columns("A")))
    End Sub
End Class

User's image

The initial display shows 2 and 3 in the first TextBox, corresponding to the selected record. However, the second TextBox just shows 1, which is the first record in A.

Is it possible to bind the second TextBox to show the corresponding column in A?

Developer technologies | .NET | Other
Developer technologies | VB
{count} votes

1 answer

Sort by: Most helpful
  1. Boruch Tkatch 141 Reputation points
    2023-11-07T16:43:16.2833333+00:00

    I'll answer my own question. The reason the code does not work is because the DataBinding in the related table needs to be the DataRelation, not the column. Also, the DataRelation works from Parent to Child, not the other way around.

    To achieve the goal being aimed for though, see the comments for one way to update it manually.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.