Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » Database connectivity using silverlight

Database connectivity using silverlight

In this article, I am going to discuss how to do database connectivity in silverlight using DataGrid.

Author Rank:
Technologies: .NET 2.0, Database, Silverlight,Visual C# .NET
Total downloads : 425
Total page views :  12462
Rating :
 5/5
This article has been rated :  1 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
DatabaseConnectivity.zip
 
Become a Sponsor



Silverlight is a new cross-browser, cross-platform implementation of the .NET Framework for building and delivering the next generation of media experiences and Rich Interactive Applications(RIA) for the web. It runs in all popular browsers, including Microsoft Internet Explorer, Mozilla Firefox, Apple Safari, Opera. The plugin required to run Silverlight is very small in size hence gets installed very quickly.

It is combination of different technolgoies into a single development platform that allows you to select tools and the programming language you want to use. Silverlight integrates seamlessly with your existing Javascript and ASP.NET AJAX code to complement functionality which you have already created.

Silverlight aims to compete with Adobe Flash and the presentation components of Ajax. It also competes with Sun Microsystems' JavaFX, which was launched a few days after Silverlight.

In this article I m going to discuss how to do database connectivity and show data in DataGrid using Silverlight Enables Web Service.

As you all know just create a new project using Silverlight Application.

And by default "Add a new Web to the solution for hosting the control" radio button is checked. And click OK.

Add a new LINQ to SQL class in App_Code folder.

And using server explorer drag and drop your table in DataClass. And you will see like this.

Now add a new Silverlight-enabled WCF Service in Web Project.

Now let's write some code on Service.cs. I am wriring all code here

using System;
using
System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;

using System.Collections.Generic;

using System.Text;

 

[ServiceContract(Namespace = "")]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class Service

{

    [OperationContract]

    public List<Vendor> GetVendors()

    {

        DataClassesDataContext db = new DataClassesDataContext();

        var mVendors = from vendor in db.Vendors

                       select vendor;

        return mVendors.ToList();

 

    }

}

I am fetching all data from my Vendor table. You can put your condition according to your requirment.

NOTE - I am putting my database file in APP_Data folder. If you want use my Vendot data.

Now add service reference in References folder.

Now let's drag and drop DataGrid on Page.xaml, and bind data using DisplayMemberBinding property.

<UserControl xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="DatabaseConnectivity.Page"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Width="800" Height="300" Loaded="UserControl_Loaded">

    <Grid x:Name="LayoutRoot" Background="White" ShowGridLines="True">

        <Grid.RowDefinitions>

            <RowDefinition Height="*" />

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="*" />

        </Grid.ColumnDefinitions>

        <my:DataGrid x:Name="VendorDataGrid" AlternatingRowBackground="Beige"

                     AutoGenerateColumns="False"

                     Width="800" Height="300"

                     Grid.Row="1" Grid.Column="1"

                     CanUserResizeColumns="True">

            <my:DataGrid.Columns>

<my:DataGridTextColumn Header="VendorId" Width="50"  DisplayMemberBinding="{Binding VendorId}" FontSize="11" />

<my:DataGridTextColumn Header="First Name" Width="120"  DisplayMemberBinding="{Binding VendorFName}" FontSize="11" />

<my:DataGridTextColumn Header="Last Name" Width="120" DisplayMemberBinding="{Binding VendorLName}" FontSize="11" />

<my:DataGridTextColumn Header="City" Width="120" DisplayMemberBinding="{Binding VendorCity}" FontSize="11" />

<my:DataGridTextColumn Header="State" Width="120" DisplayMemberBinding="{Binding VendorState}" FontSize="11" />

<my:DataGridTextColumn Header="Country" Width="120" DisplayMemberBinding="{Binding VendorCountry}" FontSize="11" />

<my:DataGridTextColumn Header="Join Date" Width="120" DisplayMemberBinding="{Binding PostedDate}" FontSize="11" />

</my:DataGrid.Columns>

</my:DataGrid>

</Grid>

</UserControl>


And this code on Page.xaml.cs

private void UserControl_Loaded(object sender, RoutedEventArgs e)

{

ServiceReference1.ServiceClient webService = new ServiceReference1.ServiceClient();

webService.GetVendorsCompleted += new EventHandler<DatabaseConnectivity.ServiceReference1.GetVendorsCompletedEventArgs>(webService_GetVendorsCompleted);

webService.GetVendorsAsync();

}

 

void webService_GetVendorsCompleted(Object sender, ServiceReference1.GetVendorsCompletedEventArgs e)

{

  VendorDataGrid.ItemsSource = e.Result;

}

 

Now debug your project and you will get this error message.

For remove this error message you need to go in propery of Web Project and Do "Use Dyanamic Ports = False".

And now set Web Project as startup project and TestPage as set as start page. And debug now. Result will look like this.

For more information I am attaching my project with database. Database is in App_Data folder. If you have any question or queries then mail me or comment me using c-sharcorner comment section.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Raj Kumar
Rajkumar is working as a senior software engineer has over 5 years experience working on asp.net, vb.net,c#, ajax and other latest technologies. He holds Master's degree in Computer Science. currently enjoying working on wpf, wcf, silverlight, mvc.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
DatabaseConnectivity.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
More operations by Milind On February 24, 2009
Hey i tried the given solution in this article. But this is only ofr database retirieval. I would like to know how to do add delete and modify operations in database and also commit the changes. I got many solutions on internet. But htey're very complex. I expect something much simple like this one for retireval is... Please help....
Reply | Email | Delete | Modify | 
how to edit and save in the datagrid to the service by sree On July 2, 2009
how to edit and save in the datagrid to the service
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved