Del via


How to connect to SQL Server from a Windows Mobile Emulator

Sometime back, I worked with a partner who had been getting SQLExceptions while connecting the SQL Server database from a Windows Mobile Emulators. If you have been getting the same problem/errors, you can try the following steps.

Here are the steps you will have to perform for connecting the SQL Server database:

1. Enable the “Windows Guest” user account (by default this is disabled and you can disable it after the job done).

2. Create a Login Name for the above account in the SQL Server (“<machine-name>/Guest)

3. Give the “db_datareader” and “db_datawriter”  access to the database, you will access on the server.

4. Cradle the emulator and deploy the application and start accessing the database.

Complete Code:

 using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Win65App
{
    public partial class Customers : Form
    {
        SqlConnection conn = null;
        SqlDataReader dr;
        SqlCommand cmd = null;
        public Customers()
        {
            InitializeComponent();
        }

        private void Customers_Load(object sender, EventArgs e)
        {
            string strConnection = "Data Source=<servername>;" +
                "Initial Catalog=Northwind;" +
                "Integrated Security=SSPI";
            try
            {
                conn = new SqlConnection(strConnection);
                conn.Open();
            }
            catch (SqlException ex)
            {
                DisplayErrors(ex);
                conn.Close();
            }
        }

        private void btnClick_Click(object sender, EventArgs e)
        {
            string strSQL = "Select [CompanyName],[ContactName] from Customers";
            try
            {
                cmd = new SqlCommand(strSQL, conn);
                dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

                while (dr.Read())
                {
                    lstCustomers.Items.Add(dr.GetString(1));
                }
            }
            catch (SqlException ex)
            {
                DisplayErrors(ex);
            }
            finally
            {
                dr.Close();
                conn.Close();
            }
        }

        private void DisplayErrors(SqlException errSQLException)
        {
            for (int i = 0; i < errSQLException.Errors.Count; i++)
            {
                MessageBox.Show("Index # " + i + "\n" + "Error:" + 
                    errSQLException.Errors[i].ToString() + "\n");
            }
        }
    }
}
 Happy Programming!

Comments