Hi

Is there a way that we can bind two textboxes together.

I have two forms. The 1st form has textbox1 and is the main form. The second form is a edit form and it contains textbox2. I would like to open form2 and see the value of textbox1 and when i change the value in textbox2 the value has been updated in textbox1. I can do this quite easily with a a data table but would like to used just textboxes.

Many thanks

Mikey

Recommended Answers

All 2 Replies

You can use the TextChanged event handler of TextBox2. In the body, just add code to copy the new value to TextBox1 as in

Dim txt As TextBox = sender
Form1.TextBox1.Text = txt.text

Jim's method is probably the simplest and qickest in performance terms, but I would recommend that the linked textbox be passed to the second form versus hard coding the reference. The TB could be passed in the form's contructor, be a property on the form or passed in the Show or ShowDialog method.

Since you asked about databinding, I'll show that method and pass the TB in Show method. Binding should be removed when not needed, so that is done in the FormClosed event handler.

Public Class Form2

  Public Shadows Sub Show(ByVal tb As TextBox)
     SetLinkedTB(tb)
     MyBase.Show()
  End Sub

  Public Shadows Sub ShowDialog(ByVal tb As TextBox)
     SetLinkedTB(tb)
     MyBase.ShowDialog()
  End Sub

  Private LinkedTB As TextBox
  Private LinkedTBBinding As Binding
  Private Sub SetLinkedTB(ByVal tb As TextBox)
     TextBox1.Text = tb.Text
     TextBox1.SelectionStart = tb.SelectionStart
     TextBox1.SelectionLength = tb.SelectionLength
     LinkedTBBinding = New Binding("Text", TextBox1, "Text", False, DataSourceUpdateMode.OnPropertyChanged)
     tb.DataBindings.Add(LinkedTBBinding)
     LinkedTB = tb
  End Sub

  Private Sub Form2_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
     LinkedTB.DataBindings.Remove(LinkedTBBinding)
     LinkedTB.SelectionStart = TextBox1.SelectionStart
     LinkedTB.SelectionLength = TextBox1.SelectionLength
  End Sub
End Class

usage:

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     Form2.Show(TextBox1)
  End Sub
commented: nice code! I've been beating myself up with databinding the last few days - fixing an MS walkthrough and all :) +0
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.