Chapter 7. Additional C# and Database Topics

There are a few other items in C# that you will find useful as you start to build applications—whether online or on the desktop. In this chapter, you can add some additional code to the projects that you’ve already built (or downloaded), or you can just put the extra code into a new project.

Referring to Connection Strings

If you think back to the Windows Forms applications that you worked on earlier, you would often have a line that looked like:

connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data       
    Source=C:\\users\\michael\\documents\\Northwind 2007.accdb";

While this is fine to do, if you had database connections on multiple forms and then you wanted to point to a different database, you would have a lot of changes to make. You may have noticed in the ASP.NET application that there was always a Web.config file that could hold the connection strings, among other settings. Well, you have the ability to create a similar file in your Windows Forms applications to do the same thing.

To do this, go to Project→Add New Item and select Application Configuration File, then leave the file name as App.Config and press Add. Then edit the App.Config file and enter the lines that you see below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
          <add name="NW_Data" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\users\michael\documents\Northwind 2007.accdb"/>
    </connectionStrings>
</configuration>

Then, either add ...

Get C# Database Basics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.