connecting to a local sql server programmatically in visual c# RRS feed

  • Question

  • I'm ging through a book and am trying to get this code to work in visual c# 2008 express edition.  however, i keep getting errors.


    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Data.SqlClient;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    namespace testDatabase


    public partial class Form1 : Form


    public Form1()



    string connectionString = "server=localhost; Trusted_Connection=yes; Network Library=DBMSSOCN; database=northwind";

    string commandString = "Select CompanyName, ContactName from Customers";

    SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, connectionString);

    DataSet dataSet = new DataSet();

    dataAdapter.Fill(dataSet, "Customers");

    DataTable dataTable = dataSet.Tables[0];

    foreach (DataRow dataRow in dataTable.Rows)


    lbCustomers.Items.Add(dataRow["CompanyName"] + "(" + dataRow["ContactName"] + ")");






    I get this error:

    An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.)



    I get the same error even when I change the connection string to this:

    Data Source=mels-comp,1433; Initial Catalog=Northwind; User Id=sa; Password=password;Network Library=DBMSSOCN;


    I have no problems databinding with data controls, in case that helps.  I just want to learn how to do this stuff programmatically.


    I have already gone through the steps in this article: so I have already enabled local and remote settings, the sql server browser service, and I have created exceptions in windows xp's firewall.


    What am I missing here?


    Thanks in advance

    Sunday, March 23, 2008 10:35 AM