SQL Server CE With vs 2010

29
©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. Building Standalone Data-Driven Applications using SQL Server Compact 4.0 and Visual Studio 2010 This free book is provided by courtesy of C# Corner and Mindcracker Network and its authors. Feel free to share this book with your friends and co-workers. Please do not reproduce, republish, edit or copy this book. Mahesh Chand Aug 2011, Garnet Valley PA

Transcript of SQL Server CE With vs 2010

Page 1: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Building Standalone Data-Driven

Applications using

SQL Server Compact 4.0

and Visual Studio 2010

This free book is provided by courtesy of C# Corner and Mindcracker Network and

its authors. Feel free to share this book with your friends and co-workers. Please

do not reproduce, republish, edit or copy this book.

Mahesh Chand

Aug 2011, Garnet Valley PA

Page 2: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Message from the Author

Thank you for being a part of C# Corner and the Mindcracker Network, a free online community for IT

developers and professionals.

I would like to thank Dan Sullivan for checking for the technical accuracy and grammatical errors. I would

also like to thank Nipun Tomar for providing the code samples.

I have always been a big believer and advocate of free knowledge and education to all. To continue this

belief, I personally have start writing free distributable books for our members. Please feel free to share

this book with your friends and co-workers.

Also, do not forget to share your knowledge and spread the word around about C# Corner and the

Mindcracker Network.

Cheers!

Mahesh Chand

Microsoft MVP, Visual C#

Founder, C# Corner and Mindcracker Network

“It’s not the words but your karma defines you.” – Mahesh Chand, 2011

Page 3: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Technical Reviewer

Dan Sullivan is a sophomore at Drexel University, studying Computer Science. During his freshman year, he competed at the 2011 Microsoft Imagine Cup. His project, based in Windows Phone 7, placed as a US finalist, making up one of the ten teams. Ever since, he’s been working on WP7 applications, even recently taking on developing the C# Corner one.

Page 4: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Building Standalone Data-Driven Applications using SQL

Server Compact 4.0 and Visual Studio 2010

Introduction

Microsoft SQL Server Compact 4.0 (SQL Compact onwards) is a free SQL Server embedded database

ideal for building standalone desktop, web, and mobile applications that need local data storage.

This book covers the following topics:

Need of a Compact Database

SQL Server Compact 4. Features

Installing SQL Server Compact 4.0

SQL Server Compact Toolbox

o SQL Server Compact Toolbox UI

o Create a Database

o Create a Table

o Add Data

o Execute Queries

Programming SQL Server Compact 4.0

o ADO.NET Data Provider for SQL Server Compact 4.0

o Establishing a Connection

o Fetching and Displaying Data

o Add, Update, and Delete Data

Using ADO.NET Entity Framework Model

Need

While SQL Server and Oracle are good for large central data storage, we often find ourselves in need of

small and local standalone data storages that can be shipped and deployed with the applications on

client computers. I started my programming career with MS-Access as the local data storage on client

computers with SQL Server being the central repository. The front-end application was built in Visual

Basic 4.

SQL Server Express is another option as a local database but it cannot be used on smart devices and

tablets.

Page 5: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Features

The following is a list of SQL Server Compact 4 features.

Lightweight

Supports desktop, web server, and mobile devices

Single file deployment

Free to use and distribute

Fully embeddable architecture

No administration required

Single file, code-free database format

Support for ClickOnce, XCopy, MSI, CAB, and non-admin embedded installation options

Supports all Microsoft Windows embedded, mobile, desktop, and server operating systems

Supports a rich subset of Transact-SQL syntax and SQL Server data types

Microsoft Visual Studio 2010 integration

Supports ADO.NET, LINQ to SQL, LINQ to Entities, and the ADO.NET Entity Framework

Supports multiple concurrent local connections

You can download the latest version of Microsoft SQL Server Compact 4.0 here:

http://www.microsoft.com/download/en/details.aspx?id=17876

After installing SQL Server Compact 4.0, you need some kind of user interface to a create database,

tables, and manage data. The Microsoft team just introduced SQL Server Compact Toolbox for Visual

Studio 2010 that can be used to work with SQL Compact.

SQL Server Compact Toolbox

SQL Server Compact Toolbox download is a Visual Studio extension developed and contributed by Erik E.

Jenson. Once installed, you may access it within the Visual Studio 2010 IDE. You can find more details

and the latest updates on Erik’s personal blog here: http://erikej.blogspot.com/. A complete

documentation can be found here: http://sqlcetoolbox.codeplex.com/documentation

SQL Server Compact Toolbox supports SQL Server Compact version 3.5 and 4.0 versions. You may

download it here: http://sqlcetoolbox.codeplex.com/

Here are some key features of SQL Server Compact Toolbox.

Page 6: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

List all SQL Server Compact Data Sources defined in Server Explorer

Launch directly from Server Explorer

SQL Editor

Script tables, including data, both DDL and DML

Script entire schema, optionally with data, from SQL Server Compact and SQL Server 2005/2008

databases

Import to SQL Server Compact from a SQL Server 2005/2008 database or a CSV file

Migrate from SQL Server Compact to SQL Server and SQL Azure

Migrate from SQL Server to SQL Server Compact

Create database diff scripts, compare with a SQL Server Compact or even a SQL Server database

Editor with syntax coloring

Parse SQL scripts

Display graphical estimated and actual execution plan

Check query duration

Rename tables

Generate detailed DGML files for visualizing table columns and relationships (requires VS 2010

Premium or higher to view)

Generate an Entity Data Model (EDMX) in the current project for both 3.5 and 4.0 in any

applicable project (WPF, WinForms, Class Library)

Generate a Windows Phone DataContext (.cs) in the current project

Add object description to databases, tables and columns

Remove invalid connection definitions from the Toolbox (and Server Explorer)

Create and manage SQL Server Merge Replication subscriptions

Data types node with documentation tooltips lists the 18 available data types

Compact Toolbox UI

You can access the SQL Server Compact Toolbox from Server Explorer as you see in Figure 1.

Page 7: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 1

You may also access SQL Server Compact Toolbox from the Tools menu of Visual Studio 2010 as you see

in Figure 2.

Figure 2

Figure 3 shows the empty SQL Server Toolbox with no database.

Page 8: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 3

Figure 4 shows the various options when you right click on the empty node.

The “Add SQL Server Compact 4.0 Connection” menu option allows us to create a new database or

connect with an existing database.

Note: SQL Server Compact Toolbox does not refresh automatically when any

changes are made. You must use the Refresh icon to see the changes. I have sent a

note to Erik. Hopefully, he will make it auto-refresh in the next version.

Page 9: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 4

On the Connect window in Figure 5, we can browse a folder and provide a database name, size in MB,

password and it will show us the connection string to establish a connection with the database.

Page 10: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 5

Click OK to create a database.

Once a database file is created, a single physical .sdf file should be located at the given location.

Server Explorer

You may also use Visual Studio Server Explorer to connect to a SQL Server Compact database and work

with it. When you connect to a database, you need to select Microsoft SQL Server Compact 4.0 from the

data source list. See Figure 6.

Page 11: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 7

If you right click on the database, you will see options to expand, show data and others. The data in

Server Explorer looks like Figure 8.

Figure 8

Page 12: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Create a Database

A database is nothing without tables and data. Let’s create a database table and add some data to it. We

can execute SQL queries using the SQL Editor, available in the Toolbox.

Right click on the database name and select “Open SQL Editor”. See Figure 6.

Figure 6

Now, let’s create a database table.

Build a CREATE TABE SQL statement that looks like Figure 7 to create a table named Authors with ID,

Name, and BookTitle columns. Click the Execute option on the editor to run the query.

Page 13: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 7

Now if you refresh the Toolbox and expand Tables node, you will see Authors table with the columns

and their types. See Figure 8.

Figure 8

Page 14: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Now, let’s build an INSERT statement to add data to the table. Figure 9 adds a row to the table.

Figure 9

Let’s view the data added to the database. Figure 10 shows a SELECT statement that fetches data from

the database. Once executed, the output looks like the rows displayed at the bottom in Figure 10.

Page 15: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 10

Programming SQL Server CE 4.0

In previous sections, I discussed how to use SQL Server Compact Toolbox to create and manage SQL

Server Compact 4.0 databases. Now, let us look at the programming aspect of this. In this section, I will

focus on establishing a connection with a SQL Server CE database, fetching and displaying data in data-

bound controls, and adding, updating and deleting data.

There are two data access technologies to work with SQL Server CE database – ADO.NET and LINQ. In

this book, we will use ADO.NET.

Adding Assembly Reference

ADO.NET provides an ADO.NET Data Provider for SQL Server CE to establish a connection and work with

SQL Server C# 4.0 databases. The data provider classes resides in the System.Data.SqlServerCe.dll

assembly. Before you could use any classes, you must add a reference to the

System.Data.SqlServerCe.dll assembly to your project.

Right click on the project name in Solution Explorer and Browse System.Data.SqlServerCe.dll. On my

machine, the path is C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop but

your path may be different. If you could not locate it, search your machine for it. See Figure 11.

Page 16: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 11

Before we use any ADO.NET Data Provider for SQL Server CE objects , we must import the following

namespace.

using System.Data.SqlServerCe;

Establishing a Connection

The following is the syntax of creating a SqlCeConnection object.

using (SqlCeConnection connection = new SqlCeConnection(@"DataSource=C:\Database\CSharpCornerDB.sdf"))

The following is the syntax of creating a SqlCeConnection object with the password.

using (SqlCeConnection connection = new SqlCeConnection(@"Data Source=C:\Database\CSharpCornerDB.sdf;Password=maheshsharp"))

Page 17: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

The Application

Let’s build a WPF application that can be used to display, add, update, and delete data. The application

UI looks like Figure 12. As you can see, the “Get Data with ADO.NET Button” retrieves and displays

author data in a ListBox control.

Figure 12

The Add, Update, and Delete buttons are used to add, update, and delete data read from the given

TextBox conrols.

Accessing Data

Once a database connection is established, we can execute any SQL statement such as SELECT, UPDATE

or DELETE to fetch, update, or delete data respectively.

Page 18: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

The code snippet in Listing 1 executes a SELECT SQL statement and puts the data from Authors table into

a DataSet. After that, the DataSet is bound to a ListBox control.

// Create a Connection using (SqlCeConnection connection = new SqlCeConnection(@"Data Source=C:\Database\CSharpCornerDB.sdf;Password=maheshsharp")) { connection.Open(); // Get data SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT ID, Name, BookTitle FROM Authors", connection); DataSet ds = new DataSet("Authors"); adapter.Fill(ds); listBox1.DataContext = ds; }

Listing 1

Since we are going to use this code repeatitively, I’m going to create a single method called

LoadAuthorsData that retrieves all the data from the Authors table. As you can see from Listing 2, I

created a SELECT SQL statement, execute it using a SqlCeDataAdapter, and call the Fill method of

DataAdapter that puts all the data into a DataSet. After that, I simply set the DataContext of the ListBox

control to the DataSet and call UpdateLayout to refresh the data.

private void LoadAuthorsData() { // Create a Connection using (SqlCeConnection connection = new SqlCeConnection(connectionString)) { connection.Open(); // Get data SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT ID, Name, BookTitle FROM Authors", connection); DataSet ds = new DataSet("Authors"); adapter.Fill(ds); listBox1.DataContext = ds; listBox1.UpdateLayout(); } }

Listing 2

Now, as you can see in Listing 3, I call LoadAuthorData on the “Get Data with ADO.NET” button click

event handler.

Page 19: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

private void GetDataButton_Click(object sender, RoutedEventArgs e) { LoadAuthorsData(); }

Listing 3

Add, Update, Delete

OK, now let’s write code for the Add, Update, and Delete button event handlers.

Listing 4 shows the Add button’s click event handler. I created an INSERT SQL statement using values

read from the Name and BookTitle TextBox controls and execute the SQL statement using the

SqlCeCommand.ExecuteNonQuery method.

private void AddButton_Click(object sender, RoutedEventArgs e) { // Create a Connection using (SqlCeConnection connection = new SqlCeConnection(connectionString)) { connection.Open(); string query = "INSERT INTO Authors(Name, BookTitle) VALUES('"; query += NameTextBox.Text + "','"; query += BookTextBox.Text + "')"; SqlCeCommand command = new SqlCeCommand(); command.Connection = connection; command.CommandText = query; if ( command.ExecuteNonQuery() > 0) { MessageBox.Show("Author added successfully!"); LoadAuthorsData(); } } }

Listing 4

If the query is successful, I display a message and refresh data.

Listing 5 is the code for the Update button’s click event handler, where I create an UPDATE statement

and execute it.

private void UpdateButton_Click(object sender, RoutedEventArgs e) { // Create a Connection using (SqlCeConnection connection = new SqlCeConnection(connectionString))

Page 20: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

{ connection.Open(); string query = "UPDATE Authors SET Name = '"; query += NameTextBox.Text + "', BookTitle = '"; query += BookTextBox.Text + "' WHERE ID = "; query += IDTextBox.Text; SqlCeCommand command = new SqlCeCommand(); command.Connection = connection; command.CommandText = query; if (command.ExecuteNonQuery() > 0) { MessageBox.Show("Author updated successfully!"); LoadAuthorsData(); } } }

Listing 5

Similar to the previous code, Listing 6 is the code for the Delete button’s click event handler where I

create a DELETE statement and execute it.

private void DeleteButton_Click(object sender, RoutedEventArgs e) { // Create a Connection using (SqlCeConnection connection = new SqlCeConnection(connectionString)) { connection.Open(); string query = "DELETE FROM Authors WHERE ID = "+ IDTextBox.Text ; SqlCeCommand command = new SqlCeCommand(); command.Connection = connection; command.CommandText = query; if (command.ExecuteNonQuery() > 0) { MessageBox.Show("Author deleted successfully!"); LoadAuthorsData(); } } }

Listing 6

Build and Run

Page 21: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Now, you build and run the application.

Enter data into the TextBox controls and use the Add, Update, and Delete buttons to add, update, and

delete authors.

ADO.NET Entity Model and SQL Server Compact 4.0

Using the ADO.NET Entity Model is another way to build fully functional data-driven applications using

SQL Server Compact 4.0. We can actually use the SQL Server Compact Toolbox to generate the entity

model.

If you right click on the database name in the SQL Server Compact Toolbox, you will notice a menu item

called Add Data Entity Model to current Project. See Figure 13.

Page 22: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 13

Select this option and on the next screen, enter your Model name as seen in Figure 14.

Figure 14

Click OK.

This step will add the data model, called CSharpCornerDB.edmx, to your project and then you will be in

the Visual Studio Entity Model design view. See Figure 15.

Page 23: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 15

Now open the Data Sources window, select the Authors table and from the dropdown select the

DataGrid option. See Figure 16. Visual Studio 2010 allows you to add data-bound controls with CRUD

operations.

Page 24: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Figure 16

After the DataGrid option is selected, drag and drop the selected table into the designer. This action will

add a DataGrid with table columns that look like Figure 17.

Figure 17

If you look at the XAML code for the winodw in Listing 7, you will see that a DataTemplate has been

added to the Window Resources with a DockPanel for each column. A ViewSource has all been added to

the code. It is bound to the CollectionViewSource. The DataGrid has three columns.

<Window x:Class="SQLCEADONETEFSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:SQLCEADONETEFSample"> <Window.Resources> <DataTemplate x:Key="AuthorDataTemplate"> <StackPanel Height="50" > <DockPanel LastChildFill="True"> <TextBlock DockPanel.Dock="Left" Margin="0,0,10,0" Text="Author Name:" FontWeight="Bold" Foreground="Orange" Width="80"/> <TextBlock Text="{Binding Name}" /> </DockPanel> <DockPanel LastChildFill="True">

Page 25: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

<TextBlock Text="Book Title:" DockPanel.Dock="Left" Margin="0,0,10,0" Foreground="Green" Width="80" /> <TextBlock Text="{Binding BookTitle}" /> </DockPanel> </StackPanel> </DataTemplate> <CollectionViewSource x:Key="authorsViewSource" d:DesignSource="{d:DesignInstance my:Authors, CreateList=True}" /> </Window.Resources> <Grid DataContext="{StaticResource authorsViewSource}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="490*" /> <ColumnDefinition Width="13*" /> </Grid.ColumnDefinitions> <DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" Height="305" HorizontalAlignment="Left" ItemsSource="{Binding}" Margin="4,6,0,0" Name="authorsDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" Width="486" RowEditEnding="authorsDataGrid_RowEditEnding" PreviewKeyDown="authorsDataGrid_PreviewKeyDown"> <DataGrid.Columns> <DataGridTextColumn x:Name="iDColumn" Binding="{Binding Path=ID}" Header="ID" Width="40" /> <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Name}" Header="Name" Width="120" /> <DataGridTextColumn x:Name="bookTitleColumn" Binding="{Binding Path=BookTitle}" Header="Book Title" Width="250" /> </DataGrid.Columns> </DataGrid> </Grid> </Window>

Listing 7

You can modify the columns the way you like.

Now, let’s take a quick look at the code behind. A DataContext and BindingListCollectionView was added

to the code. See Listing 8.

//Create DB context CSharpCornerDBEntities cSharpCornerDBEntities = new CSharpCornerDBEntities(); //Create BindingListCollectionView to hold the authors BindingListCollectionView authorsView;

Listing 8

Page 26: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

For the Window_Loaded event, code was added that gets data and binds it to the CollectionViewSource. That is converted to a BindingListCollectionView object. private void Window_Loaded(object sender, RoutedEventArgs e) { //Find the CollectionViewSource in this window CollectionViewSource authorsViewSource = ((CollectionViewSource)(this.FindResource("authorsViewSource"))); //select authors and assign them to CollectionViewSource authorsViewSource.Source = cSharpCornerDBEntities.Authors; //create authorsView from CollectionViewSource authorsView = (BindingListCollectionView)authorsViewSource.View; }

Listing 9

That’s all. Build and run the application. You will see Figure 18 and that the data is being displayed in a

DataGrid control.

Figure 18

However, we are not done yet. To provide data save and update features, we need to complete a few more steps.

Page 27: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

First thing we need to do is, update the Binding and set Mode and UpdateSourceTrigger attributes to TwoWay and PropertyChanged respectively. Mode=TwoWay, UpdateSourceTrigger=PropertyChanged

This will ensure the binding is two way. The final code for columns is in Listing 10. <DataGridTextColumn x:Name="iDColumn" Binding="{Binding Path=ID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="ID" Width="40" /> <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Name" Width="120" /> <DataGridTextColumn x:Name="bookTitleColumn" Binding="{Binding Path=BookTitle, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Book Title" Width="250" />

Listing 10

Now, we need to ensure that when we edit data in the DataGrid, the data is being saved back to the database. To do so, we are going to add the RowEditEnding event to the DataGrid. See Listing 11. All we are doing is checking if a row is being added or edited and committing the edited row and saving the changes back to the database. private void authorsDataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) { //if view is in Adding mode, commit new if (authorsView.IsAddingNew) authorsView.CommitNew(); //if view is in Editing mode, commit edit if (authorsView.IsEditingItem) authorsView.CommitEdit(); //Save changes to the database cSharpCornerDBEntities.SaveChanges(); }

Listing 11

Now, if you edit and move to the next row, you will notice the data is being saved back to the database.

The last thing we are going to do is add the delete feature. We are going to delete the selected row

when the Delete key is pressed. We need to implement the PreviewKeyDown event of the DataGrid. In

this event all the selected records will be deleted if the view is not in add or edit mode. See Listing 12.

We are calling the DeleteObject and the Remove methods to remove an author from the database

entities and the view.

private void authorsDataGrid_PreviewKeyDown(object sender, KeyEventArgs e)

Page 28: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

{ //if delete key is pressed and view is not in adding or editing mode if (e.Key == Key.Delete && !authorsView.IsAddingNew && !authorsView.IsEditingItem) { //show confimation message if (MessageBox.Show("Are you sure you want to delete selected records?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { Authors author; var dataGrid = (DataGrid)sender; //for all selected rows in the datagrid for (int i = dataGrid.SelectedItems.Count - 1; i >= 0; i--) { author = dataGrid.SelectedItems[i] as Authors; //delete author from the datacontext if not null if (author != null) { cSharpCornerDBEntities.DeleteObject(author); //remove item from the view authorsView.Remove(author); } } //save changes to the database cSharpCornerDBEntities.SaveChanges(); } } }

Listing 12

That’s all.

Now you are good to go. Build and run your application. You can add a row by typing data in a new

empty row. You can edit an existing row by typing existing data and you can delete rows by selecting

rows and pressing the Delete key.

Summary

SQL Server Compact 4.0 is a new lightweight database that can be used to provide local database

capability to applications. In this e-book, I covered the basics of the SQL Server Compact 4.0 database,

how to install and use it. After that, I discussed a very useful tool called SQL server Compact Toolbox. In

the end, we saw two step-by-step tutorials on how to build fully-functional data-driven applications

using ADO.NET with merely a few lines of code.

Page 29: SQL Server CE With vs 2010

©2011 MAHESH CHAND. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Useful Resources

Here is a list of related useful resources.

http://www.microsoft.com/download/en/details.aspx?id=17876

http://erikej.blogspot.com/

http://sqlcetoolbox.codeplex.com/documentation

http://sqlcetoolbox.codeplex.com/

SQL Server Programming: http://www.c-sharpcorner.com/1/187/sql-server-20052008.aspx

ADO.NET Programming: http://www.c-sharpcorner.com/1/131/ado-net-database.aspx

Start C# Programming: http://www.c-sharpcorner.com/Beginners/

Got a question? Ask it here: http://www.c-sharpcorner.com/Forums/