• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • 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

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / How To Use WPF DataGrid in C#.NET

How To Use WPF DataGrid in C#.NET

February 25, 2013 by Rana Ahsan 2 Comments

WPF C# Tutorials

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

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

About Rana Ahsan

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

Reader Interactions

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.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023