How to open a different table using the same bindingsource - vb.net

Michael Meeks
Michael Meeks used Ask the Experts™
on
I have a simple Winforms App - with a database with 2 tables (tableOne TableTwo)
The form has 1 textbox that is bound to the dataset for tableOne.
There is no coding at this time.  
Run the program - Textbox shows the first record of the tableOne

The form has 1 button that says change table.
However, (when coding) - when I attempt to change TextBox from one table to another,
all I get is errors.

The database is the same - there is only 2 tables - how can I switch between the two tables for
textbox to display - when I click the button?

Thank You!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Strictly speaking TextBox can not be bound to "Table" or "Record". It's bound to table (record) field (column). When you say "There is no coding at this time" - it's incorrect also - the code is in form designer. It's look smth like this:
Dim ds As New DataSet
Dim da1 As New SqlDataAdapter("SELECT * FROM Table1", connString)
da1.Fill(ds, "Table1")
Dim da2 As New SqlDataAdapter("SELECT * FROM Table2", connString)
da2.Fill(ds, "Table2")
Dim bs As New BindingSource(ds, "Table1")
TextBox1.DataBindings.Add("Text", bs, "ColumnName")

Open in new window

If both tables have same ColumName you can just  change bs.dataMember:
bs.dataMember = "Table2"
bs.ResetBindings()

Open in new window

Otherwise you need reset TextBox1.DataBindings (I suggest using second bindinSource for that):
Dim bs2 As New BindingSource(ds, "Table2")
Private Sub Button_Click(s,e) Handles....
     Dim bs = If(TextBox1.DataSource Is bs1, bs2, bs1)
     Dim colName = If(TextBox1.DataSource Is bs1, "AnotherColumnNAme", "ColumnName")
     TextBox1.DataBindings.Clear()
    ' or
    ' TextBox1.DataBindings.RemoveAt(0)
     TextBox1.DataBindings.Add("Text", bs, colName)
End Sub

Open in new window

Michael MeeksSystems Manager

Author

Commented:
Thank You !   Although VB2017 - doesn't like your (method 2 shown) - since in 2017 it has changed.

(Informational)
IDE0017 Object initialization can be simplified pops up.

(Error)
BC30455 Argument no specidifed for parmeter "metadataChange of 'Public Overloads Sub ResetBindings(metadataChanged as boolean)

When I remove method 2 - these both go away!

Strange,  But I do thank you for steering me in the right direction.  It's a big help.

Thank You!
Mike
(Error) BC30455 Argument no specidifed for parmeter "metadataChange of 'Public Overloads Sub ResetBindings(metadataChanged as boolean)
Sorry, should be bs.ResetBindings(False)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial