Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » WPF » Show/Delete/Edit data in WPF DataGrid using LINQ to SQL Classes

Show/Delete/Edit data in WPF DataGrid using LINQ to SQL Classes

This article will demonstrates how to Show, Delete, and Edit data in WPF Data Grid using LINQ to SQL Data Classes.

Author Rank :
Page Views : 18171
Downloads : 668
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WPFDataGrid.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


This article will demonstrates how to Show, Delete, and Edit data in WPF Data Grid using LINQ to SQL Data Classes. What is LINQ to SQL?? When you want to use Language-Integrated Query (LINQ) to access data in a database, you do not connect directly to the database. Instead, you create classes that represent the database and its tables, and use those classes to interact with data. You can generate the classes through the Object Relational Designer or by running the SqlMetal.exe utility. For more information, see Object Relational Designer (O/R Designer) and Code Generation Tool (SqlMetal.exe).

SO Let's start first of all add a new item LINQ to SQL data Classes.

1.JPG

Figure 1.

Now drag and drop database table using server explorer.


2.JPG

Figure 2.


If you are using Visual studio 2008 then you need to add a reference of WPF Toolkit, you don't need to add this reference in visual studio 2010.


3.JPG

Figure 3.

Add wpf toolkit name space on your .xaml page or window whatever you using.

  xmlns:grid=http://schemas.microsoft.com/wpf/2008/toolkit

This is my DataGrid.

<Grid>

        <grid:DataGrid x:Name="MyDataGrid" x:Uid="MyDataGrid" AutoGenerateColumns="False"

                       AlternationCount="2" SelectionMode="Single" Margin="0,31,0,0">           

            <grid:DataGrid.Columns>

                <grid:DataGridTextColumn Binding="{Binding  Path=CustomerID}" IsReadOnly="True"

                                    Header="Customer ID" Width="SizeToHeader" />

                <grid:DataGridTextColumn Binding="{Binding Path=CompanyName}"

                                    Header="Company" Width="SizeToHeader" />

                <grid:DataGridTextColumn Binding="{Binding Path=ContactName}"

                                    Header="Name" Width="SizeToHeader" />

                <grid:DataGridTextColumn Binding="{Binding Path=City}"

                                    Header="City" Width="SizeToHeader" />

                <grid:DataGridTextColumn Binding="{Binding Path=Country}"

                                    Header="Country" Width="SizeToHeader" />

                <grid:DataGridTextColumn Binding="{Binding Path=Phone}"

                                    Header="Phone" Width="SizeToHeader" />

                <grid:DataGridTemplateColumn Header="Edit Row">

                    <grid:DataGridTemplateColumn.CellTemplate>

                        <DataTemplate>

                            <Button Content="Edit" Click="EditButton_Click" />

                        </DataTemplate>

                    </grid:DataGridTemplateColumn.CellTemplate>

                </grid:DataGridTemplateColumn>

                <grid:DataGridTemplateColumn Header="Delete Row">

                    <grid:DataGridTemplateColumn.CellTemplate>

                        <DataTemplate>

                            <Button Content="Delete" Click="DeleteButton_Click" />

                        </DataTemplate>

                    </grid:DataGridTemplateColumn.CellTemplate>

                </grid:DataGridTemplateColumn>

            </grid:DataGrid.Columns>

        </grid:DataGrid>

        <Button Height="23" Margin="12,2,0,0" Name="LoadButton" Content="Load Customers" VerticalAlignment="Top" Click="LoadButton_Click" HorizontalAlignment="Left" Width="126"></Button>

    </Grid>

.XAML.CS

private void LoadButton_Click(object sender, RoutedEventArgs e)

        {           

                LoadCustomers();                       

        }

 

private void LoadCustomers()

        {

           

            CustomersDataContext cd = new CustomersDataContext();

            var customers = (from p in cd.Customers

                             select p).Take(10);

            MyDataGrid.ItemsSource = customers;

            LoadButton.Content = "Customers Loaded";

        }

Now run your application, you will see output like this. When you click on Load Customers button your data will display in datagrid.

4.JPG

Figure 4. 

5.JPG 


Figure 5. 

private void EditButton_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                CustomersDataContext dataContext = new CustomersDataContext();

                Customer customerRow = MyDataGrid.SelectedItem as Customer;

                string m = customerRow.CustomerID;

                Customer customer = (from p in dataContext.Customers

                                     where p.CustomerID == customerRow.CustomerID

                                     select p).Single();

                customer.CompanyName = customerRow.CompanyName;

                customer.ContactName = customerRow.ContactName;

                customer.Country = customerRow.Country;

                customer.City = customerRow.City;

                customer.Phone = customerRow.Phone;

                dataContext.SubmitChanges();

                MessageBox.Show("Row Updated Successfully.");

                LoadCustomers();

            }

            catch (Exception Ex)

            {

                MessageBox.Show(Ex.Message);

                return;

            }

 

 6.JPG

Figure 6.  

 

private void DeleteButton_Click(object sender, RoutedEventArgs e)

        {          

            CustomersDataContext cd = new CustomersDataContext();

            Customer customerRow = MyDataGrid.SelectedItem as Customer;

            var customer = (from p in cd.Customers

                            where p.CustomerID == customerRow.CustomerID

                            select p).Single();

            cd.Customers.DeleteOnSubmit(customer);

            cd.SubmitChanges();

            MessageBox.Show("Row Deleted Successfully.");

            LoadCustomers();

        }     

7.JPG 

Figure 7.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Raj Kumar

Raj Kumar is a Microsoft MVP and Senior Software Engineer with lots of hands on experience using ASP.NET 2.0/3.5, AJAX, MVC, C#, Visual Basic .NET, SQL Server 2005/2008, Oracle, WPF, WCF, XAML and Silverlight. He has over 6 years of IT experience working most on Microsoft technologies. He holds Master's degree in Computer Science. When he is not writing code, he likes to write articles and play cricket.

Reach him at raj2511984@gmail.com 

 

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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Nice Article Sir by Dharmendra On December 9, 2009
Hello Sir
Nice article that really help,
Can you suggest any tutorial link for WPF Datagrid.
Reply | Email | Modify 
Re: Nice Article Sir by Raj On December 10, 2009
thank you dharmendra
Reply | Email | Modify 
can you suggest any ebook regarding WPG Datagrid by Dharmendra On December 10, 2009
can you suggest any ebook regarding WPG Datagrid
Reply | Email | Modify 
Re: can you suggest any ebook regarding WPG Datagrid by Syed On February 17, 2011
Hi, Very Nice Article.It helps lot....
Reply | Email | Modify 
Thanks by HOSSEIN On March 3, 2011
Thank u Dear!
Reply | Email | Modify 
DataGrid Binding to sql table by Linq and sirting the columns of that DataGrid. by Olia On March 29, 2011
Hi, I have a datagrid which is binded to the sql table (i am using linq to sql). when i present the grid , i want to be able to sort its columns by clicking its column header. so far i do not have this ability. on the other hand , when i bind another data grid to list of items that i take from this table , i can sort the datagrid by clicking its columns header. where do i make my mismake?
Reply | Email | Modify 
Well done by C On July 13, 2011
At last a decent article on how to use the datagrid and commit changes back to a database table.
Reply | Email | Modify 
errors by marius On November 17, 2011
Code throws Object not referenced to an instance of an object at the edit button function: line with var
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.