CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Development How To Use WPF DataGrid in C#.NET

How To Use WPF DataGrid in C#.NET

Rana Ahsan February 25, 2013 2 Comments


 How To Use WPF DataGrid in C#.NET    

WPF datagrid didn’t seem to be that much handy or easy to use to me as like win-form data-grid. However, that doesn’t mean it’s a lot hard to implement it. Though I didn’t able to dig much into this, I will like to share my gathered knowledge while basic practicing that should help you implement a simple WPF and c# based data-grid application easily. I will also show how to add custom button control inside data-grid and associate them with even handler properly. I am using visual studio 2010 and wpf toolkit project for this tutorial.

I am assuming you do have basic wpf application development knowledge . I will also use LinQ and DBML based database schema. So, you if you don’t have knowledge in that area, you also might want to read basic linq to sql tutorial first as well.

Let’s use the following test DBML schema that we will be referring in the rest of the tutorial:
Test DBML Schema

XAML Implementation:

In whatever type of page you are adding the data-grid to (either a window or a user control), you should first mention the wpf toolkit namespace at the header part of the .xaml file.

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

Now, let us create the XAML based data-grid layout. Besides the basic design layout of the columns, we will also have to define the ‘Binding’ property and indicate to the exact property name of the class, which instances will be bind here. We will use few from our above ‘Configuration’ class in DBML/database table. In addition to show few columns, there will be one button control as well, to delete an instance/database table row right from the WPF data-grid view. So, here is the XAML code:

<my:DataGrid x:Name="ConfigGrid" AutoGenerateColumns="False">
  <my:DataGrid.Columns>
  <my:DataGridTextColumn Binding="{Binding Path=Entry_Number}" Header="Id" Visibility="Hidden" />
  <my:DataGridTextColumn Binding="{Binding Path=Part_CatalogNumber}" Header="Part Number" />
  <my:DataGridTextColumn Binding="{Binding Path=Sensor_Type}" Header="Sensor Type Id" />
  <my:DataGridTextColumn Binding="{Binding Path=Date_Entered}" Header="Date Created" />
  <my:DataGridTextColumn Binding="{Binding Path=User_Comments}" Header="User Comments" Width="250" />
  <my:DataGridTemplateColumn>
      <my:DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
            <Button Name="btnOldDelete" Click="btnOldDelete_Click">Delete</Button>
         </DataTemplate>
      </my:DataGridTemplateColumn.CellTemplate>
  </my:DataGridTemplateColumn>
  </my:DataGrid.Columns>
  </my:DataGrid>

Notice the ‘my’ tag, which are user from the imported WPFToolkit library. If you want, you can modify it in the header and thus use a more meaningful tag in template coding. Also, additional custom control adding is very simple. Just the controls need to be added inside “DataGridTemplateColumn.CellTemplate” -> DataTemplate tag.

Load Data To WPF DataGrid:

Loading data to data-grid is very easy and efficient 🙂 . We just need to assign a list of objects to the ‘ItemSource’ property of the data-grid instance. Lets check into the code snippet:

List<Configuration> configs = ConfigurationManager.Instance.SearchConfiguration(partNumber);
if (configs == null || configs.Count <= 0)
{
   throw new Exception();
}
OldConfigGrid.ItemsSource = configs;

Whoaah! It is very simple, isn’t it? Note that, it is very possible to assign a list of objects of any type of class, not only database ones, so if you load data from api, xml etc, they are also be fine to fit in here without any problem.

Delete A Configuration:

Now, let’s have a look how we can delete a row from database with action taken from the data-grid’s custom button.

private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TVConfiguration config = (TVConfiguration)ConfigurationGrid.CurrentItem;

                if (ConfigurationManager.Instance.DeleteNewConfiguration(config.Id))
                {
                    MessageBox.Show("Configuration Deleted Successfully");
                    UserControl_Loaded(sender, e);
                }
                else
                {
                    MessageBox.Show("Configuration Couldn’t be deleted");
                }
            }
            catch (Exception err)
            {
                logger.Error(err.Message, err);
                MessageBox.Show("This row doesn't contain any data");
            }
        }

So, as we see above, to get the current instance, we can easily use the ‘ConfigurationGrid.CurrentItem’ property to get that. as soon as we get the instance, we can perform the necessary operation on that object just like any other place.

Just like this delete button, in the same we, we can implement update functionality as well.

References:

You can join the discussion on codeplex for your details query. You can ask your question here as well. I will try to answer as much possible. Hope this simple illustration will help you understand the basics of using wpf datagrid in C#.NET application. Happy coding 🙂

Related

Filed Under: Development Tagged With: .net, c#, wpf

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Comments

  1. Ramesh says

    May 8, 2013 at 1:12 pm

    Excellent tutorial, for Data grid binding, I was looking for this kind of simple one, no where else it available. you made my job easy. Thanks allot. Keep it up.

    Reply
  2. Mahesh Joshi says

    November 21, 2014 at 9:09 am

    Hello
    There is problem with datagrid which is i am getting that this datagrid is not persistant. I add checkbox column to datagrid when i am selecting some checkboxes and scrolling down the datagrid some checks
    automatically get removed and some get added. What is the solution for that? Please provide me solution for that.

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
  • Generate HTTP Requests using c#
  • Utilizing Config File In C#.NET Application
  • How To Work With Codeigniter Caching In PHP
  • LinQ To SQL Database Update Operations In C#
  • Using Supervisord Web Interface And Plugin
  • Facebook C# API Tutorials

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • S. Chalisque on PHP HTML5 Video Streaming Tutorial
  • Armorik on Generate HTTP Requests using c#
  • iswaps on PHP HTML5 Video Streaming Tutorial
  • TAKONDWA on PHP HTML5 Video Streaming Tutorial
  • rorenzo on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2022 · CodeSamplez.com ·

Copyright © 2022 · Streamline Pro Theme on Genesis Framework · WordPress · Log in