C# WinForm and Sql Server CE Tutorial
Filed Under (Blog, Development, Programming) by fakhrul on 02-04-2010
1. Create a WinForm project.
* 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.
3. Insert a new item, Local Database. Then click Add.
* Click cancel at Data Source Configuration Wizard, since we will not using this wizard for now.
4. Create table and columns like below.
5. Add reference “System.Data.SqlServerCe”.
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.




























