views:

267

answers:

1

i'm a beginner user of microsoft visual studio 2008 and i want ask of what would be the initial code to connect a visual basic 2008 form to a sql server compact 3.5. i want to create an add new account program using the above applications.

A: 

Check out connectionstrings.com for the connection string.

Some of my sample code is included below. Extraneous stuff and comments removed for clarity. It's in C# but there are plenty of tools to convert it to VB. Or you can learn another lession by manually converting it yourself ;-)

The GetAllEmployees will return a list of Employees. The list can then be processed / bound as necessary to your controls.

 public static SqlConnection GetConnection()
        {
            //TODO: Use connectionString from app.config file
            string connString = "Data Source=.\\SQLEXPRESS2008;Initial Catalog=Northwind;Integrated Security=True";

            SqlConnection conn = new SqlConnection(connString);
            return conn;
        }


public static List<Employee> GetAllEmployees()
{
    SqlConnection conn = DA.GetConnection();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandText = "SELECT * FROM Employees";

    return CreateEmployeeList(cmd);
}




private static List<Employee> CreateEmployeeList(SqlCommand cmd)
{
    List<Employee> employees = new List<Employee>();

    using (cmd)
    {
        cmd.Connection.Open();

        SqlDataReader sqlreader = cmd.ExecuteReader();

        while (sqlreader.Read())
        {
            Employee employee = new Employee
                {
                    FirstName = sqlreader["FirstName"].ToString(),
                    LastName = sqlreader["LastName"].ToString(),
                    StreetAddress1 = sqlreader["Address"].ToString(),
                    City = sqlreader["City"].ToString(),
                    Region = sqlreader["Region"].ToString(),
                    PostalCode = sqlreader["PostalCode"].ToString()
                };

            employees.Add(employee);
        }
        cmd.Connection.Close();
    }
    return employees;
}
Scott