A Closer Look at ADO.NET: The Connection Object - Using VS.NET to Create a SqlConnection Object
(Page 5 of 5 )
For the next example I will create a Windows application using VS.NET, then we will create a SqlConnection object without writing even one line of code. Create a Windows application using VS.NET and call it AdoApp2, then from the Toolbox select the Data tab.

As you can see, the Data tab contains many objects to connect and manipulate SQL Server, Oracle, ODBC and OLEDB sources. For our example we need to drag a SqlConnection object onto the form. When you drag that object onto the form, you will find that there's a panel on the bottom of VS.NET that contains the sqlConnection1 object.

We need to set the Connection String to the ConnectionString property of the SqlConnection1 object. We do that through the properties window. Note that the sqlConnection1 object on the panel must be active in order to get to its properties.

Now click the drop down menu to select a connection string or to create a new one. We will create a new one, so click on New Connection.

Now select the server name (which is MichaelServer on my machine), then select the radio button Use Windows NT Integrated Security. Next, select the database pubs. Now you are ready to test the connection through the button Test Connection. Click on it and you will get the following message box:

Click Ok then Ok. Now let's look at the code that has been generated for us behind the scenes.
In the InitializeComponent() method the following code has been generated for the Connection Object:
this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();
//
// sqlConnection1
//
this.sqlConnection1.ConnectionString = "workstation id=MICHAELSERVER;packet size=4096;integrated security=SSPI;data sourc" +
"e=MICHAELSERVER;persist security info=False;initial catalog=pubs";
Of course there's a private member called sqlConnection1 in the Form1 class. Note that the generated code has not opened the connection yet. This is enough for now. In the next article we will discuss the Command object and look at more interesting code examples.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |