r/visualbasic • • Jan 26 '21

VB.NET Help Filling a DropDown from two different databases: DataAdapter or DataReader?

[I'm working on something right now, and the "problem" that needs solving seemed interesting enough to ask about. That is, i already have a solution and am working on another. I'm just curious for comment. Perhaps i'll learn something, or better yet, find out my entire approach is flawed.]

I have a dropdown filled from Access via a function. The function that gets the data:

Private Shared Function Get_List() As DataTable
    Get_List = New DataTable

    Using Adapter As New OleDb.OleDbDataAdapter(Query, Connection_String)
        Adapter.Fill(Get_List)
    End Using
End Function

Elsewhere, the dropdown datasource is assigned:

DropDown.DataSource = Get_List()

This works nicely. Fwiw, a Sub handles Handles DropDown.DrawItem to make some fancy lines and stuff.

Anyway, now i have to change it to incorporating some other data that i decided to store in Sql Server. That is, i need to get the data from Access (as already shown) and then check if the ids also exist in the Sql Server table (where it gets another id required for this program to work). How do i incorporate the two?

I started thinking (which is usually when the problems begin) the "easiest" way would be to loop through the DataTable after it's fill()ed and delete records that don't exist in Sql Server. But that's redundant, adding records just to delete them. I'd rather not add them to the DataTable in the first place. Okay, but that requires OleDbDataReader (instead of OleDbDataAdapter) and using While OleDbDataReader.Read (or its ilk) to loop through the records and check them against the Sql Server table.

I then tried figuring out how to get a DataRow (to put in the DataTable) from OleDbDataReader. Or, is that not even an option since i'm not getting the data from a DataTable, and if i really wanted a DataRow, i'd have to create one manually by looping through OleDbDataReader's result. Or maybe, i shouldn't even bother with a DataTable, and instead just use some other object to fill the DropDown (and then change other code from DataRowView to DataRow).

Then i left last night.

7 Upvotes

4 comments sorted by

2

u/electro88 Jan 27 '21

In both of your datatables set id_1 and id_2 as the primary keys. Then .merge the datatables. After you merge, use datable.select to get the rows you need for the dropdown. Select can filter out the rows with missing id_3 or whatever you need to exclude from the results.

1

u/chacham2 Jan 27 '21

Ugh. I just realized that in List, there is one case where id_1/id_2 is not unique (another column that i do not need in this program is). As a data modeler, this design frustrates me. :) Oh well. It's what i have to work with.

In Lookup, however, it is unique. But adding the Primary Key errors out with: Column 'id_1' has null values in it. It would seem to follow database rules, that a PK implicitly includes a not null constraint.

1

u/chacham2 Jan 26 '21

You know how when you look up one thing you can get so intrigued that you can look up so many other things too? Anyway...

Apparently, DataAdapter uses DataReader internally, so there's no real difference in what in being done, except DataAdapter allows for more and because of that, has a larger footprint.

After discovering that, i changed my code to use DataReader instead. It has a little more code too, as both the query and the Connection need to be handled manually:

Using Connection As New OleDbConnection(Connection_String)
    Connection.Open()
    Using Reader As OleDbDataReader = New OleDbCommand(Query, Connection).ExecuteReader
        Get_Data.Load(Reader)
    End Using
    Connection.Close()
End Using

Getting the other dat from Sql Server was pretty much the same thing, except it uses SqlDataReader and SqlCommand instead.

I decided to pull both tables and do all the work in VB. I assume it is more efficient to pull all the data just once, instead of continuously checking one record at a time over a managed connection. With well less than 100 records in either table, looping might even be faster than making a query for each id.

So, the question is what to do with the tables? I decided to load two datatables and match them up; loop on one and lookup in the other. And that proved confusing. Furthermore, what i did was overkill. Not because i wanted to do it, but because it worked. Now i can go back and change it.

I have two datatables now. I named one list and the other lookup. List has 5 columns, Lookup has 3. The link between them is 2 columns where one, the other, or both have values.

List: text_1, text_2, id_1, id_2, codes.

Lookup: id_1, id_2, id_3.

I need Lookup.id_3 where id_1 = id_1 and id_2 = id_2, including nulls.

This seemed to knock out the idea of using DataTable.Merge() or even doing the second .Load() with upsert. No matter what i tried, it just appended the rows.

As i was moving along, i decided to update all the records and only delete them afterward. This should make showing the user which items in the list were removed from the list and why much easier to implement, should the option be desired.

Comparing the values became complicated as nulls raise an exception upon comparison. That meant all four columns needed to be tested for nulls, and only compare that which is not null. Hence i came up with this monstrosity:

Private Function Get_Mapped_Calmed_Organizations() As DataTable

    Dim Null_Columns As Integer
    Dim id_3 As New DataColumn("id_3")

    Using List As DataTable = Get_Data_From_Access()
        List.Columns.Add(id_3)

        Using Lookup As DataTable = Get_Data_From_Sql_Server()

            Null_Columns = 0 ' Default: both are not null.

            ' Go through each row in the list.
            For Each List_Row As DataRow In List.Rows

                ' Checking equality with a null value results in an error.
                ' Check the list rows for null outside the inner loop, so we check only once.
                If IsDBNull(List_Row("id_2")) Then Null_Columns = 1 ' Therefore, id_1 is not null.
                If IsDBNull(List_Row("id_1")) Then Null_Columns = 2 ' Therefore, id_2 is not null.

                For Each Lookup_Row As DataRow In Lookup.Rows
                    Select Case Null_Columns
                        Case 1 : If Not IsDBNull(Lookup_Row("id_1")) AndAlso List_Row("id_1") = Lookup_Row("id_1") Then List_Row(id_3) = Lookup_Row("id_3")
                        Case 2 : If Not IsDBNull(Lookup_Row("id_2")) AndAlso List_Row("id_2") = Lookup_Row("id_2") Then List_Row(id_3) = Lookup_Row("id_3")
                        Case Else
                            If Not IsDBNull(Lookup_Row("id_1")) AndAlso Not IsDBNull(Lookup_Row("id_2")) AndAlso
                                  List_Row("id_1") = Lookup_Row("id_1") AndAlso List_Row("id_2") = Lookup_Row("id_2") Then List_Row(id_3) = Lookup_Row("id_3")
                    End Select
                Next

                If IsDBNull(List_Row(id_3)) Then List_Row.Delete()

            Next

        End Using

        'List.AcceptChanges()
        'Display_Data_Table_In_Debug_Window(List)

        Return List
    End Using

End Function

It does work and it isn't slow. Definitely shows how i am going through it though. The next step is to test out .ToString() or whatever to get rid of all the DBNull stuff. Also, figure out how to make the second DataTable a List, or maybe a Dictionary, so the second loop is not required at all.

1

u/chacham2 Jan 26 '21

Glad i wrote that out. Helps get it clear. Anyway, .ToString() definitely works with dbnull, so the code is shortened significantly:

Private Function Get_Mapped_Calmed_Organizations() As DataTable

    Dim id_3 As New DataColumn("id_3")

    Using List As DataTable = Get_Data_From_Access()
        List.Columns.Add(id_3)

        Using Lookup As DataTable = Get_Data_From_Sql_Server()

            ' Go through each row in the list.
            For Each List_Row As DataRow In List.Rows

                For Each Lookup_Row As DataRow In Lookup.Rows
                    If List_Row("id_1").ToString = Lookup_Row("id_1").ToString AndAlso
                       List_Row("id_2").ToString = Lookup_Row("id_2").ToString Then List_Row(id_3) = Lookup_Row("id_3")
                Next

                If IsDBNull(List_Row(id_3)) Then List_Row.Delete()

            Next

        End Using

        Return List
    End Using

End Function

The issue now is that second loop. I keep thinking there is a better way to match, such as with a List or the like, and using the id itself as the index. However, i have two index columns, so it isn't that simple. Unless i made three lookups, one with one id, the second with the other, and leave the third for both. Then check which id is null (if any) and go to the correct list. If neither is null, loop through the smaller list of just those where both ids are not null.

Another way to do it would be to have a list of lists, so the ids are indexes: List_1(id_1).List_2(id_2).id_3. Is that overkill? Is there a simple solution that eludes me?