Link to home
Start Free TrialLog in
Avatar of LeighWardle
LeighWardleFlag for Australia

asked on

VB.NET - using Table Adapters - how to detect when a Table does not exist

Hi Experts,

I have some code that uses Table Adapters like this:

        Dim daLoads5 As LOADSDataSetTableAdapters.TrafficSpectrumTableAdapter

	daLoads5 = New LOADSDataSetTableAdapters.TrafficSpectrumTableAdapter
        daLoads5.Fill(ds.TrafficSpectrum)
        daLoads5.Dispose()

Open in new window


The code works fine as long as the Table (in this case: "TrafficSpectrum") exists.

But it crashes if the Table does not exist.

What Table Adapter property can I use to detect when the Table does not exist?

Regards,
Leigh
ASKER CERTIFIED SOLUTION
Avatar of Scott McDaniel (EE MVE )
Scott McDaniel (EE MVE )
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
   Private Function ExecScalar(ByVal strSQL As String, ByVal conn As SqlConnection) As Object
        Using cmd As New SqlCommand(strSQL, conn)
            Try
                Return cmd.ExecuteScalar
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error executing scalar")
                Return Nothing
            End Try
        End Using
    End Function

    Private Function TableExists(ByVal tableName As String, ByVal conn As SqlConnection) As Boolean
        Dim strSQL As String = [String].Format("IF OBJECT_ID('dbo.{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'", tableName)
        Return Convert.ToBoolean(ExecScalar(strSQL, conn))
    End Function

Open in new window

I believe there is some confusion.

Do you want to know if a table exists IN A DATABASE?

Or do you want to know if a table exists in a DATASET?

Those are two entirely different things.
When the table doesn't exists in a DATASET then ds.TrafficSpectrum produce a compile error.
Avatar of LeighWardle

ASKER

Hi Scott,

This sequence is the simplest solution:

            Try
                daLoads6.Fill(ds.HaulRoadTrucks)
            Catch ex As Exception
                '< feedback to user here>
            End Try

Regards,
Leigh