silver light data base connection

26
8/6/2019 Silver Light Data Base Connection http://slidepdf.com/reader/full/silver-light-data-base-connection 1/26 7,738,431 members and growing! (29,268 online) Email Password Sign in Remember me? Lost password? Home Articles o Chapters and Sections o Search o Latest Articles o Latest Tips/Tricks o Top Articles o Beginner Articles o Video Articles o Technical Blogs o Post an Article o Post Tip & Trick o Post your Blog o Posting/Update Guidelines o Article Competition Questions & Answers o Ask a Question about this article o Quick Answers o Ask a Question o View Unanswered Questions o View All Questions... o C# questions o ASP.NET questions o VB.NET questions o C++ questions o C#3.0 questions þÿ þÿ

Upload: dipti-ranjan-parihary

Post on 08-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 1/26

7,738,431 members and growing! (29,268 online)

Email PasswordSign in

Remember

me? Lost password?

• Home

• Articles

o Chapters and Sections

o Search

o Latest Articles

o Latest Tips/Tricks

o Top Articles

o Beginner Articles

o Video Articleso Technical Blogs

o Post an Article

o Post Tip & Trick

o Post your Blog

o Posting/Update Guidelines

o Article Competition

• Questions & Answers

o Ask a Question about this article

o Quick Answers

o Ask a Questiono View Unanswered Questions

o View All Questions...

o C# questions

o ASP.NET questions

o VB.NET questions

o C++ questions

o C#3.0 questions

þÿ þÿ

Page 2: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 2/26

o Programming Discussions

o All Message Boards...

o Application Lifecycle>

Design and Architecture

Running a Business Sales / Marketing

Collaboration / Beta Testing

Work & Training Issues

o ASP.NET

o C / C++ / MFC>

ATL / WTL / STL

Managed C++/CLI

o C#

o Database

o Hardware & Devices>

System Admin

o Hosting and Servers

o Java

o .NET Framework

o Mobile

o Sharepoint

o Silverlight / WPF

o Visual Basic

o Web Development>

CSS

Javascript

PHP

o Site Bugs / Suggestions

o Other Languages>

General Indian Topics

General Chinese Topics

• Learning Zones

o The Commerce Zone

o The Mobile Zone

o The Cloud Zone

o The Hardware Zone

o The Parallelism Zone

o The WPF / Silverlight Zone

o The SQL Zone

o WhitePapers / Webcasts

o Solutions Center

• Features

o Who's Who

Page 3: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 3/26

o CodeProject MVPs

o Company Listings

o Component & Service Catalog

o Competitions

o News

o Daily Insidero Newsletter archive

o Press Releases

o Surveys

o CodeProject Stuff 

o CodeProject VS Addin

• Help!

o What is 'The Code Project'?

o General FAQ

o Post a Question

o Bugs and Suggestions

o Site Directory

o Advertise with us

o About Us

• The Lounge

o The Lounge

o Clever Code

o Hall of Shame

o The Soapbox

» Web Development » Silverlight » General

 Licence CPOL

First Posted 11 Aug 2008

Views 138,078

Downloads 298

Bookmarked 296 times

My First Data Application in Silverlight 2By Syed Mehroz Alam | 20 Oct 2008

C#WindowsDevBeginnerSilverlight

A walkthrough of retrieving data from a database and consuming it in a Silverlightapplication.

 

Part of  The WPF / Silverlight Zone sponsored by

See Also

• More like this

Page 4: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 4/26

• More by this author

  97

Article Browse Code Stats Revisions

  4.75 (105 votes)Sponsored Links

• Download source - 1.66 MB

Table of Contents

• Introduction

• What We Will Be Covering

• Running the Sample Application

• Beware ASP.NET Programmers

• Why WCF, Can't I Access the DB directory?

• Let's Start

Page 5: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 5/26

• Generating LINQ Classes

• Creating a Silverlight WCF Service

• Adding a Service Reference to the Silverlight Project

• Creating the UI

o Adding the Assembly to Use a DataGrid Control

o UI Layouto ListBox

o DataGrids

• Writing Some Code

o Populating the ListBox

o Displaying the Orders of a Customer

o Displaying the Order Details when an Order is Selected

o Removing Some Auto-generated Columns from dgOrderDetails

• Checkpoint Reached..Run the Project

• Defining Columns

• Second Run

• Writing Data Back to the DB

• Conclusion

• History

Introduction

I started using Silverlight a few weeks ago, and it looks really amazing. Combining

the presentation powers of WPF with the strong capabilities of C#, Silverlight looks

very powerful. The main focus of this article will be to retrieve data from a database

and consume it in a Silverlight application. If you are an ASP.NET developer and

want to start exploring Silverlight, then perhaps this is the right place to start sincewe will also be looking at similarities between Silverlight and ASP.NET.

What We Will be Covering

We will be developing our first business application in Silverlight. Since almost every

business application has something to do with data and databases, we will be looking

at how data (from a database) can be displayed inside a Silverlight application.

Taking the Northwind database as an example, we will be generating some LINQ

classes, a WCF service for retrieving data, and finally, aListBox and

a DataGrid along with DataTemplates for data presentation. Our output will be a

fairly simple master-detail UI with customers, their orders, and order details. Note

that the source code of this article is written targeting Silverlight 2 RC1.

Running the Sample Application

Page 6: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 6/26

A small tweak is needed to run the sample project. By default, there will be no

startup project for the solution, so we must manually set DataApplication.Web as

the startup project by bringing up the properties window of the solution.

Beware ASP.NET Programmers

If you are an ASP.NET programmer, it may be important for you to note that the C#

code in the Silverlight project runs on the "client" and not on the server. Perhaps,

you can think of it as JavaScript. Thus, the good thing with Silverlight is that you

now have full control on the client side without knowing or writing any JavaScript (at

least, I am not good at writing JavaScript).

Why WCF, Can't I Access the DB Directory?

Well, the simple reason is that since the C# code runs on the client, our server

databases will not be accessible directly. Note that we do not have items

like DataSet or DataSource in a Silverlight project. The

namespace System.Data that contains our favorite classes is also absent. But, the

good thing is that there are other alternatives too, e.g., a WCF Service. This article is

going to demonstrate how to use a WCF service for data retrieval.

Let us Start

To start creating Silverlight applications using Visual Studio, we need to install

Silverlight tools for Visual Studio that can be downloaded from here. After installing

the add-on, two new project types, Silverlight Application and Silverlight Class

Library, will be added. We will start by creating a new "Silverlight Application"project named DataApplication.

Page 7: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 7/26

Visual Studio will then ask how we want to deploy our Silverlight application; we are

going to select "ASP.NET Web Application Project" in which we will create the LINQ

classes and the WCF service.

Page 8: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 8/26

If all things go correctly, we will be able to see two projects in our

solution: DataApplication will be our client-side Silverlight project,

while DataApplication.Web will be our ASP.NET server-side project.

Generating LINQ Classes

Our lightweight all-rounder Northwind (available from this link) is always one of the

best databases to start with. Note that the MDF is also included in the sample

project, and is connected via SQLExpress. To start generating LINQ data classes, we

need to add a new LINQ Data Classes object in our ASP.NET application.

Page 9: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 9/26

Now, using the Server Explorer, create a new data connection to the Northwind

database (either using SQLExpress, or SQL Server if you have it), and then drag the

tables Customer, Orders, and OrderDetails into the LINQ designer. One

important thing is to allow serialization of our LINQ generated data classes since

we will be transferring these objects to our Silverlight application. To achieve this,

click on some empty space in the LINQ designer and change the

property Serialization to UniDirectionalusing the Properties window.

Page 10: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 10/26

Creating a Silverlight WCF Service

Now, we are about to add a service to our server project for retrieving data. Before

Silverlight 2 Beta 2, we needed some tweaks with the standard WCF service

template to use in a Silverlight project, but fortunately, Beta 2 and newer versions

give us the "Silverlight-Enabled WCF service" template that handles all things itself.

We are going to add a new Silverlight-enabled WCF Service named DataService to

our ASP.NET project.

Page 11: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 11/26

We will write three methods in our service, one that returns all the customers, one

that returns orders of a customer, and finally, one that returns order details of a

particular order. Note that the methods must be marked with the

attribute[OperationContract] (this attribute is similar to

a [WebMethod] attribute for an ASMX service). Here is a quick implementation of 

the data retrieval methods using very basic LINQ. Add the following to

the DataService.svc.cs file:

Collapse

[OperationContract]public List<Customer> GetCustomers(){

DataClasses1DataContext datacontext = new DataClasses1DataContext();  return datacontext.Customers.ToList();}

[OperationContract]public List<Order> GetOrders(string customerID){

DataClasses1DataContext datacontext = new DataClasses1DataContext();

  return (from order in datacontext.Orderswhere order.CustomerID == customerIDselect order).ToList();

}

[OperationContract]public List<Order_Detail> GetOrderDetails(int orderID){

DataClasses1DataContext datacontext = new DataClasses1DataContext();  return (from orderdetail in datacontext.Order_Details

Page 12: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 12/26

where orderdetail.OrderID == orderIDselect orderdetail).ToList();

}

Adding a Service Reference to the Silverlight Project

That's all that was required on the server-side ASP.NET project. We have created

LINQ data classes to get data from the database and a WCF service to return those

LINQ objects. Now, we are ready to consume the service in our client-side Silverlight

project. For this, we need to add a service reference in

the DataApplication project. We can click Discover in the Add Service Reference

popup to have Visual Studio automatically find the newly created WCF service for us.

Creating the UI

A Silverlight page/control consists of a layout XAML file and a code-

behind  xaml.cs file. Typically, similar to an ASP.NET page, the XAML file contains the

layout definition (like a *.aspx  file where we define our UI), while the  xaml.cs file

contains the logic and event handlers (like our aspx.cs file). Let us start by creating

some basic layout for our application.

Page 13: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 13/26

Adding the Assembly to Use a DataGrid Control

We will display our data using the DataGrid control, but Silverlight does not include

a reference to the DataGrid control by default, so we need to add one. This process

is very similar to using a custom control in ASP.NET. Recall that we add a reference

to the appropriate DLL in the project and then add a register tag in the aspx page.To achieve this in Silverlight, add a new reference (right click on References and

select New Reference) and locate System.Windows.Controls.Data in the list

(this is the assembly that contains the DataGrid).

After this reference is added, we need to assign a namespace to this assembly in our

XAML markup. To do this, add the following to the namespace declaration of the

file Page.Xaml .

Collapse

xmlns:data="clr-

namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

The Visual Studio IDE assists us here as the following screenshot shows:

Page 14: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 14/26

UI Layout

Here's an outline of what to do: Create a Grid named LayoutRoot with three rows:

the first one for our Application Title (width=50), the third one for a status bar

(width=20), and the middle row acting as the main content holder (width=*, takes

all the space that is left). Add a title TextBlock to the first row, and an

empty TextBlock named txtStatus to the bottom row of the LayoutRoot grid.

In the middle row (the one we identified as the content holder) of 

the LayoutRoot grid, add another Gridnamed ContentRoot with two columns and

two rows; the left column with width 200 and the right column taking the rest. The

rows should be divided in the ratio 60% and 40%. In the left column of 

this ContentRoot grid, add a ListBox that spans in both rows. In the right

column, add a DataGrid for the customer orders in the first row and

another DataGrid for the order details in the second row. Tired up with my crazy

sentences, here's the XAMLified version for  page.xaml :

Collapse

<UserControl xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" 

x:Class="DataApplication.Page"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;

assembly=System.Windows.Controls.Data"  Width="Auto" Height="Auto">  <Grid x:Name="LayoutRoot" Background="White">  <Grid.RowDefinitions>  <RowDefinition Height="55" x:Name="HeaderRow" />

  <RowDefinition Height="*" x:Name="ContentRow"/>  <RowDefinition Height="20" x:Name="FooterRow"/>  </Grid.RowDefinitions>  <Grid.ColumnDefinitions>  <ColumnDefinition Width="*" />  </Grid.ColumnDefinitions>

  <!-- Heading -->  <TextBlock x:Name="txtHeader" Grid.Row="0" 

FontSize="20" Margin="5,5" Foreground="Blue"

Page 15: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 15/26

  Text="My First Data Application in Silverlight">  </TextBlock>

  <!-- A textblock in the footer to be used as an Status bar -->  <TextBlock x:Name="txtStatus" Grid.Row="2" 

FontSize="10" Margin="5,0" Foreground="Red">  </TextBlock>

  <!-- Content Holder -->  <Grid x:Name="ContentGrid" Grid.Row="1" Margin="5">  <Grid.RowDefinitions>  <RowDefinition Height=".6*" />  <RowDefinition Height=".4*" />  </Grid.RowDefinitions>  <Grid.ColumnDefinitions>  <ColumnDefinition Width="200" />  <ColumnDefinition Width="*" />  </Grid.ColumnDefinitions>

  <!-- Listbox for displaying customers -->  <ListBox x:Name="lstCustomers" Grid.Column="0" Grid.RowSpan="2"  DisplayMemberPath="ContactName"

  Loaded="lstCustomers_Loaded"  SelectionChanged="lstCustomers_SelectionChanged">  </ListBox>

  <!-- DataGrid for displaying orders of a customer 

(with autogenerated columns) -->  <data:DataGrid x:Name="dgOrders" Grid.Row="0" Grid.Column="1" 

AutoGenerateColumns="True"  SelectionChanged="dgOrders_SelectionChanged">  </data:DataGrid>

  <!-- DataGrid for displaying orderdetais for an order -->  <data:DataGrid x:Name="dgOrderDetails" Grid.Row="1" Grid.Column="1" 

AutoGenerateColumns="True"  AutoGeneratingColumn="dgOrderDetails_AutoGeneratingC

olumn">  </data:DataGrid>

  </Grid>

  </Grid></UserControl>

I will not be explaining the WPF layout in much detail in this article as there are a lot

of resources on The Code Project as well as outside; e.g., this one from Sacha

Barber. We will rather have a quick look on the markup for the ListBox and

the DataGrid.

ListBox

The listbox lstCustomers will be used for displaying the list of customers in the

database. We will be binding this listbox inside theLoaded event for which we have

registered. Note that if a ListBox is bound to some object source, it will display the

valueobject.ToString() for each of its items collection. If we want to display any

Page 16: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 16/26

other value (typically a string member of the object), we have three apparent

choices:

• Override the object.ToString() method (We are not going to do this just

for displaying the correct values in aListBox).

• Define some Data Template (this is the most flexible approach, and we willbriefly look at DataTemplates in this article when we will manually define

the columns for our DataGrid, but for now, we will skip this choice).

• Define the property to be used in the DisplayMemberPath property of 

the ListBox (fairly simple, so we will keep ourselves to this for now).

Since we want the ListBox to show the ContactName property of 

the Customer object to which it is bound, we

useDispalyMemberPath="ContactName". Also, we have registered for

the SelectionChanged event which we will handle in our code-behind file to

update the DataGrid with the selected customer's orders.

DataGrids

Currently, we are not doing anything fancy with DataGrids. We have just

configured them to auto-generate their columns when they are data bound. Note

that we also subscribed for the AutoGeneratingColumns event

in dgOrderDetails. This is a common practice, and used in conjunction with auto-

generating columns if we want to remove certain unwanted columns quickly. In this

article, we will also be looking at how to define columns manually, but for now, let us

keep it simple.

Writing Some Code

Populating the ListBox

We want to load all the customers into the listbox lstCustomers, for which we are

using the Loaded event of the ListBox. Note that all service calls in Silverlight need

to be asynchronous, so we will register a callback function where we will bind the

incoming data to the ListBox. Notice how we use the txtStatus textbox (recall

we placed this in the bottom row of LayoutGrid to provide updates to the user).

Collapseprivate void lstCustomers_Loaded(object sender, RoutedEventArgs e){

DataServiceClient svc = new DataServiceClient();  this.txtStatus.Text = "Loading customers...";

svc.GetCustomersCompleted += newEventHandler<GetCustomersCompletedEventArgs>(svc_GetCustomersCompleted);

svc.GetCustomersAsync();}

Page 17: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 17/26

void svc_GetCustomersCompleted(object sender, GetCustomersCompletedEventArgs e){  if (e.Error == null)

{  this.lstCustomers.ItemsSource = e.Result;  this.txtStatus.Text = string.Empty;

}  else

{  this.txtStatus.Text =  "Error occurred while loading customers from database";

}}

Displaying the Orders of a Customer

Now, we will write some code to display the orders when a customer in the listbox is

selected. In the SelectionChanged event handler, we will call our WCF service and

bind the data to dgOrders when it is retrieved. This time, we will use anonymousmethods to be more compact.

Collapse

private void lstCustomers_SelectionChanged(object sender,SelectionChangedEventArgs e){

Customer selectedCustomer = this.lstCustomers.SelectedItem as Customer;  if (selectedCustomer != null)

{DataServiceClient svc = new DataServiceClient();

  this.txtStatus.Text = "Loading orders...";svc.GetOrdersCompleted +=

  delegate(object eventSender, GetOrdersCompletedEventArgs eventArgs){

  if (eventArgs.Error == null){

  this.dgOrders.ItemsSource = eventArgs.Result;  this.txtStatus.Text = string.Empty;

}  else

{  this.txtStatus.Text =  "Error occurred while loading orders from database";

}};

svc.GetOrdersAsync(selectedCustomer.CustomerID);}

}

Displaying the Order Details when an Order is Selected

Similar to the listbox SelectionChanged event, we add the following code to

the SelectionChanged event of dgOrders. This time, we will try lambda

expressions.

Page 18: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 18/26

Collapse

private void dgOrders_SelectionChanged(object sender, EventArgs e){

Order selectedOrder = this.dgOrders.SelectedItem as Order;  if (selectedOrder != null)

{

DataServiceClient svc = new DataServiceClient();  this.txtStatus.Text = "Loading order details...";svc.GetOrderDetailsCompleted +=

(eventSender, eventArgs) =>{

  if (eventArgs.Error == null){

  this.dgOrderDetails.ItemsSource = eventArgs.Result;  this.txtStatus.Text = string.Empty;

}  else

{  this.txtStatus.Text =  "Error occurred while loading order details fromdatabase";

}};svc.GetOrderDetailsAsync(selectedOrder.OrderID);

}}

Removing Some Auto-generated Columns from dgOrderDetails

Note that in XAML, we set the AutoGenerateColumns property of the DataGrids

to true. Let us say we want to get rid of theOrderID column in

the dgOrderDetails datagrid. This is achieved by writing the following code in

theAutoGeneratingColumns event handler:

Collapse

private void dgOrderDetails_AutoGeneratingColumn(object sender,DataGridAutoGeneratingColumnEventArgs e)

{  if (e.Column.Header.ToString() == "OrderID")

e.Column.Visibility = Visibility.Collapsed;}

Checkpoint Reached..Run the Project

Now, our small application is ready to be viewed. Run it.. Select some customers,

view orders, edit the data displayed in theDataGrid, sort the DataGrid data by

clicking on the column headers, resize the DataGrid columns, resize the browser

window, do whatever else you want. Wasn't that cool? We will now have a look at

the DataGrid columns and templates.

Page 19: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 19/26

Defining Columns

Columns in a Silverlight DataGrid can be defined in a way very similar to what we

do in an ASP.NET. The DataGrid can accept three types of columns:

• DataGridTextBoxColumn - This column type uses a TextBlock to display

its data, and a TextBox to allow editing of its data. We need to tell which

property of the data-bound object to display, using DisplayMemberPath.

• DataGridCheckBoxColumn - This column type provides a read-

only CheckBox for displaying a boolean or nullable boolean value, and a

normal CheckBox to allow editing of that value.

• DataGridTemplateColumn - This powerful column type allows us to

define DataTemplates and select controls of our own choice just like

ASP.NET's TemplateColumn. More on DataTemplating from MSDN here.

If you want to get more, Scott Morris has a nice blog entry on column types here.

Page 20: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 20/26

So, let's use this knowledge in our application. For the sake of simplicity, we will

define only four columns: we will use aDataGridTextBoxColumn for

columns OrderID and EmployeeID. We will define

a DataGridTemplateColumn forOrderDate with a TextBlock in

its CellTemplate and a DatePicker control in its CellEditingTemplate.

Finally, we will define another TemplateColumn for Frieght. But, this time, we willdefine two controls in its CellEditingTemplate: aSlider for

increasing/decreasing the Frieght value, and a TextBlock to show the current

value of the slider. Both these controls will be placed in a horizontal StackPanel as

we can only define a single item in a DataTemplate.

Here's the code that should replace the dgOrders markup:

Collapse

<!-- DataGrid for displaying orders of a customer --><data:DataGrid x:Name="dgOrders" Grid.Row="0" Grid.Column="1" 

AutoGenerateColumns="False"  SelectionChanged="dgOrders_SelectionChanged">  <data:DataGrid.Columns>  <!-- OrderID text column -->  <data:DataGridTextColumn Header="Order ID" Binding="{Binding OrderID}"/>

  <!-- EmployeeID text column -->  <data:DataGridTextColumn Header="Employee ID" Binding="{BindingEmployeeID}" />

  <!-- OrderDate template column -->  <data:DataGridTemplateColumn Header="Order Date" Width="150">  <data:DataGridTemplateColumn.CellTemplate>  <DataTemplate>

  <TextBlock Text="{Binding OrderDate}" />  </DataTemplate>  </data:DataGridTemplateColumn.CellTemplate>  <data:DataGridTemplateColumn.CellEditingTemplate>  <DataTemplate>  <basics:DatePicker SelectedDate="{Binding OrderDate,Mode=TwoWay}" />  </DataTemplate>  </data:DataGridTemplateColumn.CellEditingTemplate>  </data:DataGridTemplateColumn>

  <!-- Freight template column -->  <data:DataGridTemplateColumn Header="Freight" Width="150">  <data:DataGridTemplateColumn.CellTemplate>  <DataTemplate>

  <TextBlock Text="{Binding Freight}"></TextBlock>  </DataTemplate>  </data:DataGridTemplateColumn.CellTemplate>  <data:DataGridTemplateColumn.CellEditingTemplate>  <DataTemplate>  <StackPanel Orientation="Horizontal">  <TextBlock Text="{Binding Freight}" Width="50" />  <Slider Value="{Binding Freight, Mode=TwoWay}"Width="100"  Minimum="0" Maximum="500" />

Page 21: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 21/26

  </StackPanel>  </DataTemplate>  </data:DataGridTemplateColumn.CellEditingTemplate>  </data:DataGridTemplateColumn>  </data:DataGrid.Columns></data:DataGrid>

In a similar way, we can use DataTemplates for our ListBox. Suppose in our

object model, we have a PictureProperty(returning a BitmapImage) of 

a Customer. Then, we could have displayed the picture in the ListBox like this:

Collapse

<ListBox x:Name="lstCustomer">  <ListBox.ItemTemplate>  <DataTemplate>  <StackPanel Orientation="Vertical">  <TextBlock Text="{Binding NameProperty}"></TextBlock>  <Image Source="{Binding PictureProperty}"></Image>

  </StackPanel>  </DataTemplate>  </ListBox.ItemTemplate></ListBox>

Note that the above code is just a sample. Since we do not have pictures in our

objects, we cannot use this snippet in our application.

Second Run

Run the project again. Double click on an OrderDate and observe how

the DatePicker pops up. Use the slider control to modify the Freight value.

Similarly, any other control or combination of controls can be used inside an item

template. Note that in this second iteration, we did not modify the *.cs file; all the

changes we did were on the layout side. This is the beauty of Windows Presentation

Foundation framework.

Page 22: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 22/26

Writing Data Back to the DB

Well, this will be too much for this introductory article. But, if you have followed how

the WCF service is used to communicate between the client and the server, you can

easily write data back to the database by creating some functions in the service and

calling them from the Silverlight application. Notice that the data bindings in this

article are two way, that is, changing the value inside a DataGrid actually changes

the value in the bound DataContext item. We just need to send these updates to

our ASP.NET project using the WCF service and handle it there to update the

database. Ronnie Saurenmann presents a couple of videoshere. He uses

a DataSet like approach, keeping the modified and the original copies of data, and

then sending only the relevant records to the server using some helper classes. I

strongly recommend watching his videos.

Conclusion

Page 23: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 23/26

Page 24: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 24/26

Member

evaluate his skills by participating in various TSQL Challenges.

His blog can be viewed athttp://smehrozalam.wordpress.com.

Article TopSign Up to vote for this article

Comments and Discussions

You must Sign In to use this message board. (secure sign-in)

 FAQ 

Noise Tolerance Layout

Msgs 1 to 25 of 97 (Total in Forum: 97) (Refresh)

Thank you . great job  adish gupta

My vote of 4  Pravin Patil, Mumbai

My vote of 5  Stephanie Agnes

Please add insert code also...  ffsdf 

My vote of 5  ffsdf 

Great Article. When r more Silverlight articles coming from u?  sudipta.

Re: Great Article. When r more Silverlight articles coming from u?  Syed Me

excellent article keep it up  keesari_anjaiah

Re: excellent article keep it up  Syed Mehroz Alam

Wow!!  rasheed1979

Re: Wow!!  Syed Mehroz Alam

This article is great! awesome! Princess Grace

Dimaculangan

Re: This article is great! awesome!  Syed Mehroz Alam

DataServiceClient  closl

Re: DataServiceClient  closl

Make this really spectacular!  larry118

Re: Make this really spectacular!  Syed Mehroz Alam

þÿ þÿ

Page 25: Silver Light Data Base Connection

8/6/2019 Silver Light Data Base Connection

http://slidepdf.com/reader/full/silver-light-data-base-connection 25/26

Re: Make this really spectacular!  larry118

very good article  firsan

Re: very good article  Syed Mehroz Alam

superb !!!  mohtarahul

Re: superb !!!  Syed Mehroz Alam

Excellent artical  070100644

Re: Excellent artical  Syed Mehroz Alam

Good work!  pwlynch

Last Visit: 6:09 24 Apr '11 Last Update: 23:20 24 Apr '11

General News Question Answer Joke Rant Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads,

Ctrl+PgUp/PgDown to switch pages.

link | Privacy | Terms of Use | Mobile 

Last Updated: 20 Oct 2008

Copyright 2008 by Syed Mehroz Alam

Everything else Copyright © CodeProject, 1999-2011

Web22 | Advertise on the Code Project

Spread for ASP.NET

FarPoint Spread for ASP.NET 5 by GrapeCity is...

www.gcpowertools.com

Resco MobileForms Toolkit

The richest, most complete and award winning...

www.resco.net

Resco MobileApp Studio

Resco MobileApp Studio is a Microsoft Visual...

www.resco.net

See Also...

Silverlight tutorial: Creating a data centric web app with DataGrid, LINQ, and WCF Web Service

A step-by-step guide for creating a...

7 Simple Steps to Connect SQL Server using WCF from SilverLight

In this article, we will look at how we can do...

Silverlight 3: Displaying SQL Server Data

This article demonstrates how to display SQL...

An Introduction to Silverlight

The definition of Silverlight, the purpose of...

A Sample Silverlight 4 Application Using MEF, MVVM, and WCF RIA Services - Part 1

Part 1 of a series describing the creation of...