How to: Connect to a Database (C#)
Updated: October 2008
Connecting to a data source is easy when you use Visual C# Express Edition. You can use visual tools to browse to a database and add a local copy to your project. When you install SQL Server Compact 3.5 with Visual C# Express Edition, you have access to a sample database named Northwind.sdf. You can connect to the Northwind database by using the Data Sources window.
You have to run Visual C# Express Edition as administrator to gain access to the Northwind database. On the Start menu, right-click Visual C# Express Edition and then click Run as administrator.
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.
To add a connection to the Northwind database
On the File menu, point to New and then click Project.
In the New Project dialog box, click Windows Forms Application, and then click OK.
A new Windows Forms project opens.
On the Data menu, click Add New Data Source.
The Data Source Configuration Wizard opens.
Click Database and then click Next.
Click New Connection.
The Add Connection dialog box opens.
In the Add Connection dialog box, if the Data source is not Microsoft SQL Server Compact 3.5 (.NET Framework Data Provider for Microsoft SQL Server Compact 3.5), click Change and select Microsoft SQL Server Compact 3.5 from the Change Data Source dialog box. Click OK.
Click the Browse button and locate the Northwind.sdf database.
The default location is drive:\Program Files\Microsoft SQL Server Compact Edition\v 3.5\Samples.
Click Test Connection to verify that the connection succeeded, and then click OK to close the dialog box.
Click OK to close the dialog box, and then in the Data Source Configuration Wizard, click Next. If prompted to copy the data file to your project, click Yes.
On the next page of the wizard, select the Yes, save the connection as check box, and then click Next.
On the Choose Your Database Objects page, expand Tables.
Select the check box for both Products and Order Details, and then click Finish.
A local database file is added to your project. Notice that a NorthwindDataSet object has been added to the Data Sources window.
In Solution Explorer, select Northwind.sdf and make sure that the Copy to Output Directory property is set to Copy if newer.
On the File menu, click Save All to save your project.