C# WinForm and Sql Server CE Tutorial

Filed Under (Blog, Development, Programming) by fakhrul on 02-04-2010

1. Create a WinForm project.

Capture14-12-2009-13.45.4901-04-2010-21.57.13

* If you are using a 64 bit platform, make sure that the target platform is x86. If not you will be facing a problem later on.

2. Create a form like this.

Capture14-12-2009-13.45.4901-04-2010-22.03.35

3. Insert a new item, Local Database. Then click Add.

Capture14-12-2009-13.45.4901-04-2010-22.05.07

* Click cancel at Data Source Configuration Wizard, since we will not using this wizard for now.

4. Create table and columns like below.

Capture14-12-2009-13.45.4901-04-2010-22.08.14

5. Add reference “System.Data.SqlServerCe”.

Capture14-12-2009-13.45.4901-04-2010-22.09.51

6. Add this code at button Add.

private void btnAdd_Click(object sender, EventArgs e)
{
    string fileName = "Database1.sdf";
    string password = "";
    string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);

    string sql = "insert into ValueList (ValueData) values ('" + txtValue.Text + "')";

    SqlCeConnection cn = null;
    try
    {
        cn = new SqlCeConnection(connectionString);

        SqlCeCommand cmd = new SqlCeCommand(sql, cn);

        if (cn.State == ConnectionState.Open)
            cn.Close();

        cn.Open();
        cmd.ExecuteNonQuery();
        MessageBox.Show("Data added");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (cn != null)
            cn.Close();
    }
}

7. Add this code at button Refresh.

private void btnRefresh_Click(object sender, EventArgs e)
 {
     string fileName = "Database1.sdf";
     string password = "";
     string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);

     string sql = "select * from ValueList";

     SqlCeConnection cn = null;
     try
     {
         cn = new SqlCeConnection(connectionString);

         SqlCeCommand cmd = new SqlCeCommand(sql, cn);

         if (cn.State == ConnectionState.Open)
             cn.Close();

         cn.Open();
         SqlCeDataReader scdr = cmd.ExecuteReader();

         listView1.Items.Clear();
         while (scdr.Read())
         {
             listView1.Items.Add(new ListViewItem(new string[] {scdr.GetInt32(0).ToString(), scdr.GetString(1)}));
         }
         scdr.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         if (cn != null)
             cn.Close();
     }
 }

8. You are done.

Comments:

One Response to “C# WinForm and Sql Server CE Tutorial”


  1. Woh ada update! Mesti bosan dok rumah sorang2. Hehe.

Leave a Reply