Click here to Skip to main content
15,891,763 members
Articles / Database Development / SQL Server

SQL Database Relation Builder

Rate me:
Please Sign up or sign in to vote.
3.33/5 (3 votes)
23 Aug 2004 52.2K   1.4K   25  
An article on automatically building the relationships between tables in a DataSet.
Public Class frmMain
    Inherits System.Windows.Forms.Form

    ' Initialize constants for connecting to the database
    ' and displaying a connection error to the user.
    Protected Const CONNECTION_ERROR_MSG As String = _
        "To run this sample, you must have SQL " & _
        "or MSDE with the Northwind database installed"

    Protected Const MSDE_CONNECTION_STRING As String = _
        "Server=(local);" & _
        "DataBase=northwind;" & _
        "Integrated Security=SSPI"
        'If you did a normal installation of Northwind, please replace the line
        'above with the line below.
        '"Server=(local)\NetSDK;" & _

    Protected Const SQL_CONNECTION_STRING As String = _
        "Server=localhost;" & _
        "DataBase=northwind;" & _
        "Integrated Security=SSPI"

    Protected DidPreviouslyConnect As Boolean = False
    Protected strConn As String = SQL_CONNECTION_STRING

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
   Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid
   Friend WithEvents btnClose As System.Windows.Forms.Button
   Friend WithEvents btnAbout As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.DataGrid1 = New System.Windows.Forms.DataGrid
Me.btnClose = New System.Windows.Forms.Button
Me.btnAbout = New System.Windows.Forms.Button
CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'DataGrid1
'
Me.DataGrid1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
            Or System.Windows.Forms.AnchorStyles.Left) _
            Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.DataGrid1.DataMember = ""
Me.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
Me.DataGrid1.Location = New System.Drawing.Point(8, 8)
Me.DataGrid1.Name = "DataGrid1"
Me.DataGrid1.Size = New System.Drawing.Size(360, 224)
Me.DataGrid1.TabIndex = 0
'
'btnClose
'
Me.btnClose.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.btnClose.Location = New System.Drawing.Point(292, 243)
Me.btnClose.Name = "btnClose"
Me.btnClose.TabIndex = 1
Me.btnClose.Text = "&Close"
'
'btnAbout
'
Me.btnAbout.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnAbout.Location = New System.Drawing.Point(208, 243)
Me.btnAbout.Name = "btnAbout"
Me.btnAbout.TabIndex = 2
Me.btnAbout.Text = "&About"
'
'frmMain
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.CancelButton = Me.btnClose
Me.ClientSize = New System.Drawing.Size(376, 275)
Me.Controls.Add(Me.btnAbout)
Me.Controls.Add(Me.btnClose)
Me.Controls.Add(Me.DataGrid1)
Me.Name = "frmMain"
Me.Text = "SQLRelationBuilder Sample"
CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

    End Sub

#End Region

   Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
      CreateDataSet()
   End Sub


   Sub CreateDataSet()
      Dim scnnNW As SqlClient.SqlConnection

      ' Display a status message saying that the user is attempting to connect.
      ' This only needs to be done the very first time a connection is
      ' attempted.  After we've determined that MSDE or SQL Server is
      ' installed, this message no longer needs to be displayed.
      Dim frmStatusMessage As New frmStatus
      If Not DidPreviouslyConnect Then
         frmStatusMessage.Show("Connecting to SQL Server")
      End If

      ' Attempt to connect to the local SQL server instance, and a local
      ' MSDE installation (with Northwind).  
      Dim IsConnecting As Boolean = True
      While IsConnecting
         Try
            ' The SqlConnection class allows you to communicate with SQL Server.
            ' The constructor accepts a connection string as an argument.  This
            ' connection string uses Integrated Security, which means that you 
            ' must have a login in SQL Server, or be part of the Administrators
            ' group for this to work.
            scnnNW = New SqlClient.SqlConnection(strConn)
            scnnNW.Open()

            'Create a new instance of the relation builder
            Dim rb As New Level54.Data.SQLClient.SQLRelationBuilder(scnnNW)

            DataGrid1.DataSource = rb.GetDataSet("Employees", Data.SQLClient.RelationDirection.Down, -1)
            DataGrid1.DataMember = "Employees"

            ' Data has been successfully retrieved, so break out of the loop
            ' and close the status form.
            IsConnecting = False
            DidPreviouslyConnect = True
            frmStatusMessage.Close()

         Catch expSql As SqlClient.SqlException
            MsgBox(expSql.Message, MsgBoxStyle.Critical, Me.Text)
            Exit Sub

         Catch exp As Exception
            If strConn = SQL_CONNECTION_STRING Then
               ' Couldn't connect to SQL Server.  Now try MSDE.
               strConn = MSDE_CONNECTION_STRING
               frmStatusMessage.Show("Connecting to MSDE")
            Else
               ' Unable to connect to SQL Server or MSDE
               frmStatusMessage.Close()
               MsgBox(CONNECTION_ERROR_MSG, MsgBoxStyle.Critical, Me.Text)
               End
            End If
         Finally
            If Not (scnnNW Is Nothing) Then
               If scnnNW.State <> ConnectionState.Closed Then
                  scnnNW.Close()
               End If
               scnnNW.Dispose()
            End If
         End Try
         frmStatusMessage.Close()
      End While
   End Sub

   <System.Diagnostics.DebuggerStepThrough()> _
   Private Sub btnAbout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAbout.Click
      ' Open the About form in Dialog Mode
      Dim frm As New frmAbout
      frm.ShowDialog(Me)
      frm.Dispose()
   End Sub

   <System.Diagnostics.DebuggerStepThrough()> _
   Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
      Me.Close()
   End Sub
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Engineer
South Africa South Africa
I'm a mechanical engineer working in the pipe manufacturing business, although programming has been my first love for the past twelve years.

My languages of choice are VB.NET, VB6 and C#, in that order. I took last year off from programming, as me and my family moved into a new house, and there were things to be done. When I started up again, I discovered that not only had my .NET abilities gone rusty, but also my VB6 abilities.

Anyway, I love programming. I think .NET is the best thing since sliced bread (coming from VB6).

Comments and Discussions