0

I am trying to create a Window's Form Application connected to a SQL Server database. I am able to connect to the database using Alteryx, Tableau, Python and using the connection wizard in Visual Studio. However, when I try and create a connection within the application it fails to connect. I have attempted to do this in multiple ways

  1. VB
  2. C# using SqlClient
  3. C# using config file (with details from tested connection)
  4. C# using ODBC driver
/*************** ODBC Driver ***************/

using System;
using System.Windows.Forms;
using System.Data.Odbc;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            string connetionString = null;
            OdbcConnection cnn;

            connetionString = "Driver={SQL Server Native Client 11.0};
            Server=********;Database=********;Uid=********;Pwd=********;"; 

            cnn = new OdbcConnection(connetionString);

            try
            {

                cnn.Open();
                MessageBox.Show("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Can not open connection ! ");
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

However, when I run this code I get the following error

Activated Event Time Duration Thread Exception: Exception thrown: 'System.Data.Odbc.OdbcException' in System.Data.dll ("ERROR [08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: A non-recoverable error occurred during a database lookup.

ERROR [HYT00] [Microsoft][SQL Server Native Client 11.0]Login timeout expired ERROR [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online."). Exception thrown: 'System.Data.Odbc.OdbcException' in System.Data.dll ("ERROR [08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: A non-recoverable error occurred during a database lookup.

ERROR [HYT00] [Microsoft][SQL Server Native Client 11.0]Login timeout expired ERROR [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.") 16.78s [22724]

For comparison, when I run a similar script in Python I have no trouble connecting to the data

/******** Python using Jupiter Notebook ********/

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                      'Server=********;'
                      'Database=********;'
                      'Uid=********;'
                      'Pwd=********;')

cursor = conn.cursor()
cursor.execute('SELECT * FROM [********].[dbo].[********]')

for row in cursor:
    print(row)

Why can't I connect via a Windows Form Application if I can connect all the other ways. I am assuming that I all the TCP/IP settings should be fine? Plus I have already established a connection via Visual Studio.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Damien Minter
  • 309
  • 5
  • 11
  • Possible duplicate of [Why am I getting “Cannot Connect to Server - A network-related or instance-specific error”?](https://stackoverflow.com/questions/18060667/why-am-i-getting-cannot-connect-to-server-a-network-related-or-instance-speci) – Thom A Oct 28 '19 at 22:31
  • Ummm, I have gone through a number of similar posts and already checked I am using the default instance and can accept except external connections. I am not able to check TCP / IP settings as I don't have the right privileges, but as I have managed to connect with Python, I am assuming these are ok – Damien Minter Oct 29 '19 at 01:57
  • https://www.connectionstrings.com/sqlconnection/ – Mary Oct 29 '19 at 07:58
  • There is also a class in the framework that might help https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnectionstringbuilder?view=netframework-4.8 – Mary Oct 29 '19 at 08:04
  • @Mary - Thanks, I have already used both those resources and haven't been able to crack it. I also followed a youtube video that created a separate class for the connection but that didn't work either. Unless anyone can see something wrong with the code above I have missed, I am wondering if is something specific to Windows Forms (vs Visual Studio Application) including specific firewall / other permissions. I am really lost with this one!! – Damien Minter Oct 29 '19 at 13:05
  • Do you still have the SqlClient version of the code? I'd keep with that one and diagnose from there (post it if you still have it). – HardCode Oct 29 '19 at 16:46
  • I will do tomorrow once I am back in the office. Thanks – Damien Minter Oct 30 '19 at 11:40

1 Answers1

0

I changed the ODBCConnection to SQLConnection. This worked for me, but I am by no means an expert. I do work better in VB.NET so this code was converted to C# using Telerik Code Converter. I have also posted the VB.NET code at the bottom in case something messed up in the conversion.

C# Code

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            TestConnection();
        }

        private void TestConnection()
        {
            string connectionString = null;
            SqlConnection cnn;
            SqlConnectionStringBuilder cnBuild = new SqlConnectionStringBuilder();
            cnBuild.DataSource = "Server";
            cnBuild.InitialCatalog = "databaseName";
            cnBuild.UserID = "userid";
            cnBuild.Password = "password";
            // connectionString = "Driver={SQL Server Native Client 11.0};Server=********;Database=********;Uid=********;Pwd=********;"
            cnn = new SqlConnection(cnBuild.ConnectionString);

            try
            {
                cnn.Open();
                MessageBox.Show("Connection Open ! ");
                cnn.Close();
            }
            catch (Exception __unusedException1__)
            {
                MessageBox.Show("Can not open connection ! ");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }
}

VB.Net Code


Imports System
Imports System.Windows.Forms
Imports System.Data.SqlClient

Namespace WindowsFormsApplication2
    Partial Public Class Form1
        Inherits Form

        Public Sub New()


            TestConnection()
        End Sub

        Private Sub TestConnection()

            Dim connectionString As String = Nothing
            Dim cnn As SqlConnection
            Dim cnBuild As New SqlConnectionStringBuilder
            cnBuild.DataSource = "Server"
            cnBuild.InitialCatalog = "databaseName"
            cnBuild.UserID = "userid"
            cnBuild.Password = "password"
            cnn = New SqlConnection(cnBuild.ConnectionString)

            Try
                cnn.Open()
                MessageBox.Show("Connection Open ! ")
                cnn.Close()
            Catch __unusedException1__ As Exception
                MessageBox.Show("Can not open connection ! ")
            End Try
        End Sub

        Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        End Sub

        Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
        End Sub
    End Class
End Namespace
  • I will give this a go tomorrow, once I am back in the office - Thanks – Damien Minter Oct 30 '19 at 11:39
  • Hi @DjJazzyJeffTN - The C code had a few bugs, so I tried the VB. Not sure if it connected or not. It didn't time out after 15 seconds but did send a message saying it has connected. I need to mess around with the code to get it to open the connection on a button click to check, but haven't had a chance atm – Damien Minter Nov 01 '19 at 11:26
  • I was afraid of that with the C# converter. I am glad that the VB code worked for you. Since you said that it worked, would you mind marking this as the answer then? Since the issue seems to be the incorrect connection string. Thanks and happy coding. – DjJazzyJeffTN Nov 04 '19 at 19:04
  • I need to test it actually made a connection. Apologies bit busy with other things right now. I will come back to this and mark correct when I get a spare minute. Thanks – Damien Minter Nov 05 '19 at 23:11
  • Wondering if you ever tested the code that I shared with you? – DjJazzyJeffTN Feb 18 '20 at 17:00
  • Apologies... I was "released" from the company before I managed to give this a proper go. – Damien Minter Oct 17 '20 at 12:38