Question

Data Tables, querying using SQL and returning results to a new data table.

Asked by: NeilGrant

Hi,

I am working with a windows application and I have a dataset with several datatables loaded from individual tables of an Access database.  I want to be able to create other datatables in the dataset that have the results of a "relational" SQL query on the existing datatables.   Then I will use the resulting datatable as a datasource for a binding which is in turn a datasource for a datagridview that users work with.

So, for example, if I have a datatable called Users with a field called StateID and a datatable called States with fields StateID and StateName I want to run a SQL command like

    SELECT Users.*, States.StateName FROM Users, States WHERE Users.StateID = States.StateID

then return the results to a new datatable in the dataset.

I can get the results I want by using a dataadapter for each relational query, however this means connecting back to the database all the time for reading and writing.  My cunning plan is to avoid this (due to slow network links) and allow the user to load the data they need once, then create additional datatables as required in memory to hold the related data.  As the users make changes, I will do the updating back to the memory based datatables that were loaded using dataadapters.  When appropriate I will use the update command of the dataadapters to get all the results back to the database.

I have looked at adding a relation to the dataset but this doesn't seem to be able to produce a datasource that will display in a datagrid view as described in my example above.

So as always any help welcome.

Neil

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-09-05 at 14:45:06ID21979017
Tags

data

,

datatables

,

from

,

sql

,

table

Topic

Microsoft Visual Basic.Net

Participating Experts
2
Points
500
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. binding a DataGrid to Datasets and DataAdapters in VB.NET
    Hi, I am trying to make a simple VB.NET windows application. I have a small SQL Server Database with a connection from a "SQLConnection" component. I also have placed a "DataAdapter" component on my VB FORM. How do I get a DataGrid control to show the rec...
  2. DataAdapter and Datatable - ThnX !
    I'm not sure how to do this, and at lost trying to figure it out. Plz help. I want to be able to do this: objConn = CreateConnStr() 'returns sqlconnection dataAdapter = New System.Data.SqlClient.SqlDataAdapter(strSql, objConn) dataSet = New DataSet If Pag...
  3. VERY COMPLICATED datagrid/dataset/dataadapter quest…
    I need some help with this very complex problem. Please be patient as I try to explain and read carefully. I have the need to create an editable datagrid that will display data retrieved from my SQL Server database and allow the user to insert, update, and delete rows in thi...
  4. DataAdapters, DataSets and DataGrids
    Hi all, I'm having a bit of a hardtime here with all the Data-things!! Everytime I setup a dataadapter, dataset via the visual interfaces, it puts all the code in the #Region " Windows Form Designer generated code " Firstly can someone tell me what the Me. means!...
  5. Persisting DataAdapter
    (newbie alert) Situation is: > Have built and am using myDataAdapter to fill myDataTable from MS-SQL myDBTable > Am doing stuff with myGridview to update myDataTable > (Custom: the DataTable updates are all custom Rows.Add's, not Gridview edit/updates) > No...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: cubixSoftwarePosted on 2006-09-06 at 03:48:51ID: 17461973

Hi

When you create your data relation, you can use this as a datasource as follows...

dim ds as dataset
dim r as datarelation

' do all code to create your dataset with data from Users and States


' create relation
r = New DataRelation("UserStates", ds.Tables("User").Columns("StateID"), _
                                                                            ds.Tables("States").Columns("StateID"))
ds.Relations.Add(r)


datagrid.datasource = ds
datagrid.datamember = "User.UserStates"


' now format the display of the datagrid using tablestyles etc. so only required columns are displayed


HTH

 

by: grayePosted on 2006-09-06 at 06:00:48ID: 17462746

What you're describing is an in-memory SQL engine...  

Take a look at the following article that describes how you can use the ordinary SQL Select command against DataTables in a "disconnected" DataSet without going back to the underlying database.

http://home.hot.rr.com/graye/Articles/SQL_Engine.htm

The article also has downloadable VB.Net source code for the SQL_Engine demonstration project.

 

by: NeilGrantPosted on 2006-09-06 at 15:50:06ID: 17467015

Thanks guys, both look promising I cannot get to this project for a day or so I will get to them as soon as I can and give you feedback.

Regards,
Neil

 

by: NeilGrantPosted on 2006-09-06 at 23:28:05ID: 17468516

HTH,

I have tried the code you have suggested but it does not produce the result I require.  It populates the datagridview with the records that contain only the first entry in the parent table.  In the example this would be the first StateID.
It also does not show the value of the parent table the should be substituted into the child table.  So in my example it is only showing the StateID not the string from the States table.

So I get a result like

Field1, Feild2, StateID, Field3
Value, Value, 1         , Value
Value, Value, 1         , Value
Value, Value, 1         , Value

When I used the good ol' SQL query on the source database I get something like below which is what I want.  
Field1, Feild2, StateID, Field3
Value, Value, Ohio    , Value
Value, Value, Essex  , Value
Value, Value, Ohio    , Value
Value, Value, Tasmania  , Value
Value, Value, Ohio    , Value
Value, Value, Essex  , Value
Value, Value, Essex  , Value
Value, Value, Tasmania  , Value
Value, Value, Tasmania  , Value

Incidentally I am not working with Users and States but this is a simple example.

I have read again about datarelations and it still seems to me they are all about using code to loop through child tables for a given value of a parent table, as opposed to getting a datasource that shows all the results.

I am missing something?

Neil


 

by: NeilGrantPosted on 2006-09-06 at 23:34:08ID: 17468533

graye,

I was initially excited about your solution but I noticed you said that ...
"...there is no support for any DDL statements (ALTER, CREATE, or DROP) nor any other DML statements (INSERT, UPDATE, or DELETE) ..."

The second part of my "cunning plan" described above, was that I would detect changes in the related data, then work out which "source" table records needed updating and do so in memory.  Then I would use their dataadapters to update the database.  I am correct in assuming that your SQL_Engine does not support the updating of datatables in memory?

Neil

 

by: cubixSoftwarePosted on 2006-09-07 at 01:27:00ID: 17468903

Hi

When you create your dataset, do not use your query above, but simply retrieve the records for Users and States and merge them,


for example

ds.Merge(<the users table>)
ds.Merge(<the states table>)

then build the datarelation.

I am doing this myself using winForms .NET2003 and works quite well


 

by: grayePosted on 2006-09-07 at 04:47:01ID: 17469850

My SQL_Engine will take the 2 dataTables and produce a 3rd DataTable.   Just like in a "real" database, the result set has no ties back to its source.   It's a one-way proposition.

I noticed that your example was just a simple read-only "look up" for column.   Is that indicative of the real data?   If so, you may be able to accomplish the same concepts with just a DataRelation and some clever tricks with the DataGrid class.   That way the user will be able to edit the data and have it saved back in the normal way.

 

by: NeilGrantPosted on 2006-09-10 at 20:51:27ID: 17491657

HTH,

Sorry I was off line for a while.  I tried using the merge above then build the relation.  The net result was the same as before.

I created a new dataset as below, used the merge command on the tables in the existing dataset I had, without error.  (I am now showing the real project names)

        Dim dsMainNew As New System.Data.DataSet
        dsMainNew.Merge(dsMain.Tables("Images"))
        dsMainNew.Merge(dsMain.Tables("Drives"))


Then I set the relation as below
        Dim MyRelNew As DataRelation
        MyRelNew = New DataRelation("MainRelNew", dsMainNew.Tables("Drives").Columns("DriveNum"), dsMainNew.Tables("Images").Columns("DriveNum"))
        dsMainNew.Relations.Add(MyRelNew)

Then I set the datagridview source as below.
        Me.dgvMain.DataSource = dsMainNew
        Me.dgvMain.DataMember = "Drives.MainRelNew"

The datagridview shows all the records from the Images table that has the DriveNum from the first record in the Drives table.  There is no substitution of the DriveNum value with the DriveLet (the other field in the Drives Table).

I read up on the merge command and it seems to me to be more about updating changes from one object to another instance of the same object that may have different records in it.

I am sorry if I am missing the point but I still can't get this to work.

Neil



 

by: NeilGrantPosted on 2006-09-10 at 23:54:39ID: 17492106

graye,

Thanks for the confirmation.  I guess I am a bit reluctant to step outside the standard functionality offered by VS.NET.  This is not a reflection on your work, but more on my inexperience.

I am interested in following up your comments about " ... just a simple read-only "look up" for column.   Is that indicative of the real data?"
The answer is that there is a table called Images that will have 3 or more "look ups".  However the users must be able to add values to each of these tables.  For example on table is States and if a record is enterred for which a state does not exist, the user needs to be able to create the record in the States Table.

You, like HTH, mention a DataRelation but as you can see in my comments to them, I can only seem to get records shown from the "child" table for the first record in the "parent" table.

Whatever the outcome of how to display the related data.  I am still assuming once my code detects changes/additions are required in any of the four or more tables in the dataset, that I will be able to locate the record needing changing, and make the change in memory, then eventuall call the update method of the dataadapter for each table.

Do you see a problem with this?

Neil

 

by: grayePosted on 2006-09-11 at 04:50:17ID: 17493624

First of all, the Merge() command is for reconciling changes/additions/deletions for rows in a table.   So, it is not designed to do an SQL JOIN type operation.

OK, if you want to stick with just the "store bought" solution, then you could try using DataColumn expressions to perform the "lookup" for the related rows.   Here is an example from http://home.hot.rr.com/graye/Articles/DataRelations.htm

      ' create a relationship between two of the tables
      ' arguments are Name, ParentCol, ChildCol, create_foreign_key
      ds.Relations.Add(New DataRelation("CategoryProducts", ds.Tables("Categories").Columns("CategoryID"), ds.Tables("Products").Columns("CategoryID"), False))

      ' add a column from a related table.
      dc = New DataColumn("CategoryName")
      dc.DataType = GetType(String)
      dc.Expression = "Parent(CategoryProducts).CategoryName"
      ds.Tables("Products").Columns.Add(dc)

      ' Since a Parent relationship can only return one row, this is a safe expression. However,
      ' if you had a child relationship, you'd have to include an aggregate in order to guarantee
      ' that the function would return just one row"Max(Child(CategoryProducts).UnitPrice)"
      DataGrid1.DataSource = ds.Tables("Products")  
       



 

 

by: NeilGrantPosted on 2006-09-12 at 23:31:33ID: 17509471

graye,

Apologies for the delay, this is a job I cannot focus on a lot for now.   Plus I am still very much learning .NET and database connections.  Now the grovelling is out of the way THANKS HEAPS!  Your solution is great for me.  

I have started to read your web site as well.  You present the ideas well.  Congratulations on that.

I didn't realise you could add columns to a DataSet.DataTable without mucking up the ability to use the command builder for the original table to get your updates back to the database.

Plus, as a novice, I had no idea there was a "methodology" involving the DataColumn.Expression that could so neatly emulate a join like you have shown.  It is even interactive on the DataGridView ie if I change the ID field from the child table the related value is updated immediately, fantastic.

Before I accept your answer, I hope you won’t mind me being a bit cheeky and asking your advice on the next directly related problem I face now.

Thanks to your help I can now present a DataGridView to users that has the joined values and only shows the relevant fields to the user.  So the ID field in the child table is hidden and only corresponding values are shown from the parent tables.

I want to be able to offer the user either editing via another form which handles a single records at a time with some smarts to help them, or editing directly on the DataGridView.

The single form will be relatively easy (I believe) for me to control the issue of displaying values from the parent tables.  One such table is Countries which has CountryID field and a CountryVal field.  So I am picturing I will show a combo box of the current values with the correct one highlighted for the record.  If they change the value in the combo box (CountryVal) or add a new one, I will change the CountryID value in the child table and update the Countries table if necessary.

However, I would very much appreciate your thoughts on how to combine a combo box selection with the DataGridView.  As my project stands now, I can make the DataGridView editable for all the fields that are in my child table as gathered from the database.  However, not surprisingly the “joined fields” like CountryVal are not editable in the DataGridView.

Do you have any suggestions as to how, upon entry into the CountryVal column, they could be presented with a combo box of options.  It would be OK to me if adding a new Parent record was not allowed when editing on the DataGridView.

Any ideas?

I will understand if you wish me to issue this as separate question.  Let me know.

Neil

 

by: grayePosted on 2006-09-13 at 05:48:57ID: 17511397

Ok... I think I'm following...

Actually, you can accomplish a simple combobox lookup inside the DataGridView without using DataRelations (or any of the other items we've discussed up till now).  This was the "clever tricks" idea that I mentioned waaaay back.

Here is an example...

    Private ds As New DataSet

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' load some data from NorthWind
        LoadData()

        DataGridView1.DataSource = ds.Tables("Products")   '<- the "base" table

        ' create a custom DataGridViewColumn that will perform a database "lookup"
        Dim dgvc As New DataGridViewComboBoxColumn
        dgvc.DataPropertyName = "CategoryID"                    '<- the column from the "base" table
        dgvc.ValueMember = "CategoryID"                           '<- the column to look up in the "child" table
        dgvc.DisplayMember = "CategoryName"                    '<- the string value you want displayed
        dgvc.DataSource = ds.Tables("Categories")               '<- the child table
        DataGridView1.Columns.Add(dgvc)
    End Sub

    Private Sub LoadData()
        Dim con As New OleDbConnection
        Dim da As New OleDbDataAdapter
        Dim cmd As New OleDbCommand

        ds.Tables.Clear()
        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\NorthWind.mdb"
        cmd.Connection = con
        da.SelectCommand = cmd

        ' fill a few tables from the Northwind database
        con.Open()
        cmd.CommandText = "Select * from Categories"
        da.Fill(ds, "Categories")
        cmd.CommandText = "Select ProductName, CategoryID, UnitPrice, UnitsInStock, UnitsOnOrder from Products"
        da.Fill(ds, "Products")
        con.Close()
    End Sub

 

by: NeilGrantPosted on 2006-09-13 at 20:45:18ID: 17517598

graye,

You're a champion.  The last idea worked well also.   It has revealed more possibilities for me.

I thank you again for revealing some new concepts I hadn't yet discovered.

The points are well earned indeed.

I hope you catch my further questions on .NET

Regards,
Neil

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...