Referencing a BindingSource Using a String Based Variable

Tony Gardner
Tony Gardner used Ask the Experts™
Hello Experts.
This has probably been asked a thousand times, but I can't seem to find how to do this,
Basically, I want to reference a BindingSource using a string based variable, but VB.NET won't let you cast from a string to a Binding Source.
Knowing how to do this would help me reduce a great deal of code.
For example, let's say that I have 10 different Binding Sources in my project. For simplicity sake, let's just say that they are named A_BindingSource, B__BindingSource, C_BindingSource, and so on up to j_BindingSource, Now for each one I want to be able to add a record, delete a record and save the record. I've gone ahead and put Tags on each button on the various forms to indicate the table name and it's function. There are other ways to do this, but that's what I'm using now. So if I write a Sub to use a Select Case, I would need one for each permutation. But if I could use a variable, it would be so much simpler. I'm imagining something like this:
Dim TagData() As String = sender.Tag.ToString.Split("|") ' Stored as Table | Function
Dim TableID As String = TagData(0) ' For example, "A_"
Dim BtnFunc As String = TagData(1) ' For example, "New"
Select Case BtnFunc
  Case "New"
    TableID & "BindingSource".AddNew()
  Case "Rem"
    TableID & "BindingSource".RemoveCurrent()
  Case "Sav"
    TableID & "BindingSource".EndEdit()
    Me. & TableID & "TableAdapter.Update(Me.TheDataSet." & TableID & ")"
End Select

Open in new window

Obviously, the above code is very fictional, but I'm hoping that you get the "gist" of what I'm after.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2017
Hi Tony;

You could set up a Dictionary control to hold a reference to the BindingSource controls and get the one you need by using a string name something like the following.
Dim bsControls As Dictionary(Of String, BindingSource)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    '' In the constructer load the Dictionary with the BindingSource
    bsControls = New Dictionary(Of String, BindingSource)
    bsControls.Add("bs1", BindingSource1)
    bsControls.Add("bs2", BindingSource2)
    bsControls.Add("bs3", BindingSource3)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim bs = bsControls.Item("bs2")
    '' bs is now the reference to the BindingSourec you need in this case BindingSource2
End Sub

Open in new window

Tony GardnerSr. Programmer/Analyst


Thanks so much, Fernando. This works great! Now if only I could do the same with TableAdapters, I would be able to handle the Save operations as well!


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