.NET 3.5 SP1 and WPF DataGrid CTP are out now!


UPDATE: the WPF DataGrid v1 has just released.  For more information, see this post.  The information below still applies, but the new post contains the additional features as well as an updated sample.  Check it out!


As you might have heard, .NET Framework 3.5 SP1 and Visual Studio 2008 SP1 are out today! There are a ton of blogs that point to the download links so I’ll just point you over to one of them, Lester’s blog. In addition to the SP1 release, the WPF DataGrid CTP is also out today! Check it out here for the list of DataGrid features as well as 3.5 SP1 features in the Controls area that has enabled the DataGrid. Our awesome PM, Samantha, has a nice video introducing the basic usage of the DataGrid. Oh yea, and you can download the binaries and source code here! 3.5 SP1 is required to use the DataGrid binaries so be sure to download that goodness.


Overview

Does DataGrid need an introduction? Well, maybe I’ll just point out some of the WPF specifics to get you started. DataGrid subclasses from MultiSelector which subclasses from Selector which subclasses from ItemsControl. So like ListBox or ComboBox, DataGrid is an extention of an ItemsControl. With that in mind, the DataGrid has the concept of rows and cells but to match the pattern of ItemsControl, the collection of rows is the Items property. Cells are sub-items of a particular item and are defined by the DataGrid.

How do I use it?

There are a ton of sub-features and ways to customize and tweak the DataGrid. For this first post I just want to start with the very basics. Ok, here we go. DataGrid derives from ItemsControl, so just like we’ve done in the past with ListBox, bind the DataGrid.ItemsSource to your data source.

<dg:DataGrid ItemsSource=”{Binding Source={StaticResource people}}”>

In this example people represents a collection that derives from ObservableCollection<Person> where Person has some properties that represent a general person (first name, last name, id, etc). Ok, that’s it. If you run a project with that you will get a full set of rows and columns with each cell bound to each property on the Person item. By default the DataGrid will auto-generate columns for you and the generated columns will be a specific type of column based on the type of properties you have in your data source. It also automatically creates the necessary bindings for each data source property on each column. It does appear very magical but hopefully I will be able to demystify a lot of its behavior over a series of posts. Here are some other things you get or can do right out of the box as an end-user for CTP:

· Resize columns: hover over the end of a header, then click and drag.

· Reorder columns: click on a column header and drag over a different area.

· Auto-sort data in a column: click on a column header and the items in the column will toggle from ascending to descending

· Multi-column sorting: SHIFT + click on multiple column headers

· Selection: Default mode is FullRow and multi-row selection

· Navigation: all the basic navigation you expect in a spreadsheet

· Edit cells and rows: select a column and press F2 or double-click to open the cell for edit. Press ‘ESC’ to cancel and/or ‘Enter’ to commit the changes.

· Delete rows: select a row and press ‘Delete’.

· Add new rows: navigate to the bottom row and double click a cell to open it for edit.

· Clipboard Copy

· Freeze columns

Of course there is a bunch more you can do to customize these default features as well as the internals of the DataGrid. I’m going to do a series of posts introducing many of the sub-areas of DataGrid. In the meantime, I made a sample where I bind many of the DataGrid DPs to CheckBoxes and ComboBoxes so you can tweak things in real-time and play around with it. Enjoy!

UPDATE: You can also download the updated V1 Sample here. 

clip_image002


I’m also going to be doing a series of posts on the DataGrid.  I’ll be updating this with the future DataGrid posts. 


Learn more:


Dissecting the Visual Layout


Stock and Template Columns


Working with DataGridComboBoxColumn (Part1)


Working with DataGridComboBoxColumn (Part2)


Overview of the editing features in the DataGrid


Design-time Walkthrough


5 Random Gotchas with the WPF DataGrid


Samples:


ScrollViewer with ToolTip


Custom sorting, column selection, single-click editing


Tri-state sorting


Styling rows and columns based on header conditions


Clipboard Paste


Locking input to the row being edited


Dynamically updating a DataGridComboBoxColumn


New Item Template


Frozen Row Sample


Exploring MVVM: Grouping with the DataGrid


Launching a custom dialog to edit items in the DataGrid


 

DataGridCTPSample.zip

Comments (97)

  1. Rudi Grobler says:

    Well, their is a huge hype surrounding the release of .NET Framework 3.5 SP1 &amp; Visual Studio 2008

  2. When I reviewed some 3rd party WPF components out there I noticed the fact most of them showcased a datagrid

  3. Josh Smith says:

    Vincent,

    I watched Samantha’s video, and something struck me as odd.  Why is the DataGrid’s HeaderVisibility property not of type Visibility?  Every other WPF property I can think of whose name ends with "Visibility" is of type Visibility.  I think that property should be renamed, perhaps to something like "Headers" or "VisibleHeaders".

    Josh

  4. Oh man, naming for DataGrid was a killer for us as we and the Silveright folks would sit in a conference room for an hour to an hour an a half on multiple occasions just discussing type, method, and event names.  For some things some people had lots of varying opinions and I can’t remember the final reasoning for all of them.  For the Visibility enums, which was decided on early, I think we had a similar discussion that you brought up if I still remember.  Like I said, I don’t remember the final reasoning but I actually prefer the word "Visibility" somewhere in the type name of the enum for the headers visibility.  Maybe DataGridHeadersVisibilityMode would have made it differ for other properties of type Visibility.  There are two other DataGrid types that follow a similar pattern, DataGridGridLinesVisibility and DataGridRowDetailsVisibilityMode.  I need to check back with Samantha on why that last one has a "Mode" on the end and the others do not.

    "VisibleHeaders" is an option which would be much different than "HeadersVisible" but I’m guessing you thought about that one and why it might confuse people into thinking it’s of type bool like winform’s DataGridView.ColumnHeadersVisible.  Let me talk with Samantha and a few others on your thoughts and also our reasoning behind our current decision.  I’ll get back to you on it.

    Thanks,

    Vince

  5. I’m going to be dissecting and discussing the DataGrid visuals and how they are all assembled together

  6. Can that sample be included in the stuff on CodePlex? Seems like it would be really helpful.

  7. Overview The DataGrid uses a set of DataGridColumns to describe how to display its data just like a GridView

  8. Joel, I’ll see what I can do to get it up there.  I’m glad that you find it very useful!

  9. See Sharp says:

    Get a grip on the DataGrid – Snoop your way out of your troubles

  10. Sandeep (India) says:

    We are looking for following features:

    Will they be included in future? If yes, when can we expect?

    1. Footer

    2. Save Datagrid Layout

    3. Merge Cells in Header/Footer/Body

    4. Data Filtering (single / multi column)

    5. Column Customization (To hide a column User

      can drag column to an area or on right click of a

      column give option to hide column)

    6. Customized Summary Field where User can enter his

      formula which can consist of some condition

    7. Exporting Grid to Excel/PDF/CSV

    Thank you very much for gr8 work.

    Regards,

    Sandeep

  11. Julie says:

    I’m playing with your sample and I can’t figure out what the checkbox "IsFrozen" is supposed to do. I was expecting it to freeze the column so that it could not be scrolled out of view, but it didn’t do that. Thanks!

  12. Sorry for the confusion.  For the column customization part, IsFrozen and IsAutoGenerated are read only values that tell you what their state is.  I should have not made them checkboxes.  If you update the FrozenColumnCount or the DataGrid.AutoGenerateColumns checkbox on the left you will notice that the column IsFrozen and IsAutoGenerated will update accordingly.  

    I’ll update the sample so they are not mistaken for editable properties.

  13. shahab says:

    Thanks for the great article, could you please or anyone guide me in the right direction. I need to get the cell value of the cell clicked in the dg. Basically I want to open a new window when a user clicks on the row to pass the cell clicked value.

    any advice would be muchly appreciated

  14. wonderliza says:

    I found no samples for the moment, for stuffs like CommitingEdit etc… Do you know where we can find some ?

  15. wonderliza,

    I’m not aware of samples for the editing stuff just yet.  I do plan on talking about that in upcoming posts.  Stay tuned.

    -Vince

  16. Ron Larvick says:

    The big question I always have and hope for is if this grid will allow copy and paste from the clipboard.  Because many business applications I work with, users want to copy Excel data to their grid.  Either one cell to many, or multiple cells to the same number of cells.

    Can you do that with the new grid?

  17. Ron,

    In the current bits you do have the ability to copy data from the DataGrid to the clipboard.  Formats such as csv and html are supported out of the box.  For other formats we have made it extensible to create your own.  Clipboard paste is currently not supported but a relatively easy solution exists with the current implementation (through SelectedCells which gives you DataGridCellInfo).

  18. Karl says:

    In the CTP drop, MS in included the source code for the DataGrid. I was really surprised.  It is a great learning tool.

    Will it get released from RTM like that?

    Can we extend and customize the code and put that into products?

  19. Karl,

    Yes the final v1 source will be released on CodePlex like the CTP.  Later down the line, the bits will be integrated into PresentationFramework.dll.  

    As far as integrating public changes to the WPF DataGrid, no.

  20. Hardik says:

    Hi, can anybody tell me that how we can bind Images that comming from database to DataGrid?

    and what kind of images we can bind?

    thaks

  21. Hardik,

    Binding an image coming from a database is no different than binding to any other property.  If the image was store in the database as a stream of bytes then you would have to create the image on the client side when the table is retrieved.  If the image was stored as a filename string then of course you would have to have the image exist on the client side.

    As far as the types of images that can be bound, they are: .bmp, .gif, .ico, .jpg, .png, .wdp, and .tiff

  22. Hardik says:

    Hi Vincent, I am facing one more problem today. That I am trying to bind my read-only proprty to grid in "OneWay". but it still display an error message "A TwoWay or OneWayToSource binding cannot work on the read-only property".

    But the strange thing is that I am binding it as "OneWay" explicitly.

    Any advice? thanks

  23. This is a known issue and will be fixed in the v1 release.

  24. gnobber says:

    Hi,

    I tested the datagrid and are having problems (in some areas). I bind the grid to an ObservableCollection with contents and it worked fine. But if the collection does not contain any item, you cannot add a new row via the grid. This only happens when AutoGenerateColumns = True.

    And also, say the grid has items. When you click on the last row (the NEW row) and begin edit, then click back on some other row, a new row is generated even though you did not enter a value on the then was new row. Is this by design?

  25. gnobber,

    For the first issue, see the comments from this post, http://blogs.msdn.com/vinsibal/archive/2008/05/27/using-ieditablecollectionview-with-dynamically-generated-gridviewcolumns.aspx.  It describes the conditions for not being able to add a new row when the count is zero.

    For the second issue, this is by design.  A row will be committed when you press enter or click anywhere outside of the row.  If you don’t want the behavior when you click outside of the row, you can listen to the CommittingRow event and cancel it there.

  26. matt says:

    Hi,

    This is possibly a very silly question, but, how does one bind to a DataTable? I’m simply trying to bind the grid to a table in an SQL database, but I’m stumped as to how to do it.

  27. Matt,

    To bind to a DataTable you will need to set it’s DataView to the ItemsSource.  DataTable has an API, DefaultView, that you can set to the ItemsSource.  I have an example in the sample on this post, http://blogs.msdn.com/vinsibal/archive/2008/08/28/wpf-datagrid-working-with-datagridcomboboxcolumns-part-2.aspx

  28. There have been several questions on the WPF CodePlex discussion list relating to styling rows and columns

  29. Morten says:

    Hi Vincibal,

    I have built my own CustomDataGrid for copy-paste based on your example, which I’m very grateful for. However, I would like the user to be able to add new rows to the grid by pasting many rows. In your example rows are only overwritten but no new ones are created. I’ve tryed to figure out how to manage that but I think I need some help… Thank you!

  30. Morten says:

    Thank you vincibal. It works great!

  31. the believer says:

    Hi,

    I’ve read your blog about and it looks like the datagrid is shaping up to be a flexible control. Can’t believe I just read this today. I have a question though. Does this datagrid support ierarchical views? If not, will it? Thanks!

  32. the believer,

    Currently it does not support hierarchical view.  This is a frequent request and will be considered in future release.  I appreciate you taking the time to read my blog.  If you have any other feedback or questions just let me know.

  33. HariOm says:

    Hi,

    Adding the new row in DataGrid will (by default) call the default constuctor of object (whose collection is binded to datagrid).

    so, is it possible to call contructor other than default constructor when adding a new row?

    Any help?…. thanks in advance…

  34. Hariom,

    Only the default constructor can be called through IEditabledCollectionView (which is what the DataGrid is using).  The way to work around it is to attach to the DataGrid.InitializingNewItem event.  From there you have access to the new object and you can update any properties on the new object before it is added to the DataGrid.

  35. HariOm says:

    Thanks vinsibal for quick reply. That is the option I am following right now but according to my business logic, it’s not healthy way to do.

    So, will this feature be in next release or not?

    thanks

  36. HariOm,

    Currently there isn’t a plan to support this but it will be added to the list of feature requests.  Thanks for your feedback.

  37. Corey says:

    Anybody tried binding to a collection that contains abstract objects?  When I make an attempt at adding a new row it will report to me that the type of object it’s trying to instantiate is abstract and cannot be instantiated.  I would like to be able to go with the default object in this case but I’m not sure yet how to communicate that to the grid.  Is there an event before ‘InitializingNewItem’ I could possibly use to inject this logic?

  38. randix says:

    Hi Vincent,

    Thanks for the article. I’ve also read your article about the DataGridComboBoxColumn and when I tried it out, I noticed that the DataGridComboBoxColumn is read-only. I want to be able to implement an AutoComplete feature when a user edits the contents of a cell. Any ideas?

  39. Corey,

    Have you tried something like this,

    MyCollection : ObservableCollection<AbstractObject>?

    I’ve tried it with an interface and as long as you have items in the colleciton you will be able to add new items.

  40. randix,

    Try something like this:

    <dg:DataGridComboBoxColumn.EditingElementStyle>

                           <Style TargetType="ComboBox">

                               <Setter Property="IsEditable" Value="True" />

                               <Setter Property="IsReadOnly" Value="False" />

                               <Setter

                           </Style>                    </dg:DataGridComboBoxColumn.EditingElementStyle>

  41. Mike Bredbury says:

    Great demo but can you show us all how to have a simple button on the screen that will delete the selected row from the DataGrid in code-behind? Go on, please show us, sounds simple!

  42. Randy Maquilla says:

    Hi Vicent,

    Is it possible to get the coordinates of a cell (left, top, right, bottom)? I want to be able to show a usercontrol directly below the cell, or directly to the right of a cell, etc. Thanks!

  43. Spiderman says:

    Hi,

    When is the official release (of datagrid)? And will MS release a downloadable .NET 3.5 with SP1 bundle?

  44. Corey says:

    Is it possible to change how the ENTER key works when focus is on the grid? Say, I want the focus to be on the next column of the same row, not on the next row when I press ENTER.

  45. Spiderman,

    I can’t say the official release date but you don’t have very long to wait.  

    What do you mean about a downloadable .NET 3.5 SP1 bundle?  

  46. Mike Bredbury,

    You can take two approaches for this one.  You can call the DeleteCommand programmatically or you can recreate the DeleteCommand.Execute code.  

    If you call the Command programmatically, you will have to also programmatically set focus on the CurrentCell as focus will move away when you click the button.  

    If you decide to just recreate the Execute code, you have to do these steps:

    1. check if the row is still being edited, if so cancel.

    2. call IEditableCollectionView.Remove(itemToRemove)

    3. update selection to be place on a new item still in the collection

  47. Corey,

    You can listen to the PreviewKeyDown event and look for the enter key.  From there you can change focus to the next cell if you want and cancel the default enter operation.

  48. Randy Maquilla says:

    Hi Vincent,

    Is it possible to get the coordinates of a cell (left, top, right, bottom)? I want to be able to show a usercontrol directly below the cell, or directly to the right of a cell, etc. Thanks!

  49. MarkOro says:

    Hi Vincent,

    First of all thanks for your articles. I find your blog the most helpful for the current datagrid.

    I’ve been playing around the datagrid and am quite satisfied with what is available with it. But I have stumbled into a problem. And, seeing that many asks for your help with regards to the datagrid, I would like your help too.

    While editing a text column on the datagrid, if you set focus on another control, the text column commits the values and the editing control (textbox) gets hidden. Is there a way for the textbox to stay visible and editable even if focus changes, say to a listview? Thank you very much.

  50. CloverField says:

    Hi Vincent,

    I got a problem and im hoping you can help me out. I bound a datagrid to a List<T>. Only one column is bound: a Name column. What I can’t seem to figure out is I need to get the unique ID a new object added to the grid. But since there is only a Name column, when you add a new column, of course only the Name property of T has a value. I can’t think of a way how to get the T’s ID after editing Name. Any ideas?

  51. Frank says:

    Hi Vince!

    is there a post out there somewhere than can give me an example of how to access the content of in individual cell (code behind XAML c#) .. ie datagrid populated with toList() six columns accross 10 rows

    I want to get the content of the cell that intersects the fourth rown and the second column..

    Thanks

  52. ulrakhma says:

    Hi Vincent, is that possible for one column last one or any one to spring or fill the remaining of the grid area automatically?

    Lev

  53. MarkOro,

    You can listen to the CommittingEdit event and cancel the operation in our specific scenario.  I haven’t tried it out for your scenario so if you run into other issues, just let me know.

  54. Randy Maquilla,

    Could you explain more on how you want to go about adding additional controls to the DataGridCell.  The reason I ask is b/c there’s a lot going on in the CellsPresenter Measure and Arrange for things like virtualization, star columns, etc.  If you are willing to wait (which you won’t have to wait very long now), the final version of DataGrid has a RowDetails control that you can add anything you want.  It should also give you an idea of ways to customize the experience.  You also have access to the Cell’s template itself which you can customize the experience as well.

  55. ulrakhma,

    If you make the column a star width then it will fill the remaining space.

  56. ulrakhma says:

    So, I cannot use AutoGenerateColumns and ItemsSource BOUND TO Collection? Should I do something similar to WinForm DataGridView — no autogenerate, manually create datagrid column, set HeaderText, AutoSizeMode, DataPropertyName, and then add it to grid’s column collection?

    Thank you for your answer

    Lev

  57. ulrakhma,

    You can still use Auto-column generation.  What you’ll have to do is listen to the AutoColumnsGenerated event and there set the last column’s width to a star value.

  58. Josh Smith says:

    Hi Vincent,

    How do you get the current row?

  59. Josh,

    You can get the current row through DataGrid.CurrentItem.

  60. Josh Smith says:

    Hi again,

    About the current row, could you elaborate a bit? The CurrentItem returns an object and if I call GetType(), it returns the type that is bound on that row. How exactly do I get the current row from CurrentItem?

  61. Volker says:

    I am trying to get the new Wpf datagrid to work with an EditableRootList(CSLA Framework). When I update one of my items in the collection through editing a cell in the grid everything works fine first time changes are made. I can see the events being fired in the grid and Save is called on the item. The properties passed in are the new ones after editing.

    Second time, same cell, same picture although the item passed seems to be the old one. IsDirty not checked, properties not modified. Of course the Save is ignored in BusinessBase.

    Looks like the Grid is not replacing the references after the first update. However the UI is showing the correct values after the modifications although they are never modified in the DB. I am using a StaticResource and the CslaDataProvider. Csla Version 3.5.1 with VS 2008 Express C# :Net 3.5 Sp1

    Am I missing something or is it really an issue with the new DataGrid?

  62. regev says:

    hi,

    when will the next version of the DataGrid be released (I saw that it will be part of the PDC)?

  63. Josh Smith says:

    Vincent,

    About the current row I asked you, how do you exactly use CurrentItem to get the row? The CurrentItem is of type whatever object type when the grid is bound to a collection. Do you mean I find the CurrentItem in the bound collection and use the item’s index in the collection?

  64. Josh Smith,

    That is correct.  You can get the current DataGridRow by mapping the index of CurrentItem in the collection to the DataGridRow.  This thread shows an implementation of GetRow(), http://www.codeplex.com/wpf/Thread/View.aspx?ThreadId=34065.

  65. regev,

    That’s a good question that you ask.  The DataGrid v1 is going to be released this week at PDC!

  66. Lelouch says:

    Vincent, I don’t get this. I have a datagrid bound to a List<MySubject>. MySubject is like this:

    public class MySubject

    {

    public string Description {get; set;}

    public string Units {get; set;}

    public Subject Subject {get; set;}

    }

    public class Subject

    {

    public string Name {get; set;}

    }

    I’ve got three columns bound like this:

               DataGridTextColumn colAccount = new DataGridTextColumn();

               Binding b = new Binding("Subject.Name");

               b.Mode = BindingMode.TwoWay;

               colAccount.DataFieldBinding = b;

               colAccount.Header = "Name";

               dgrdChild.Columns.Add(colAccount);

               DataGridTextColumn colDescription = new DataGridTextColumn();

               b = new Binding("Description");

               b.Mode = BindingMode.TwoWay;

               colDescription.DataFieldBinding = b;

               colDescription.Header = "Description";

               dgrdChild.Columns.Add(colDescription);

               dgrdChild.ItemsSource = _SubjectList;

    The problem is, when I add new values to an empty datagrid, the name column won’t commit, but description column does. Does it have anything to do with the Name column bound to an aggregate class?

  67. Carter says:

    How do you resolve this, Vincent? If you have a datagrid in a modal window and a Cancel button (isCancel=True), when you click a cell of the datagrid and start typing, and if the first character you type is ‘c’, the Cancel button is triggered. So instead of being able to type, the window gets closed. How do you prevent this?

  68. Volker,

    I’m not as familiar with the EditableRootList code.  From what you have said it is hard to say where the issue lies.  Could you provide a code snippet?

  69. Lelouch,

    Try the sample here, http://blogs.msdn.com/vinsibal/archive/2008/10/22/wpf-datagrid-and-the-wpftoolkit-have-released.aspx.  It has a data source with nested data and works correctly.  Maybe that can help you out.

  70. Carter,

    Why is the Cancel button triggered when you type ‘c’? Is that intended?

  71. Carter says:

    Hi Vincent,

    That’s what I can’t get. Cancel’s hot key is ‘C’ (_Cancel) and IsCancel = True. I tried adding an event handler to Cancel_Click and whenever I press ‘C’ when focus is on datagridcell (but not in edit mode), instead of entering edit mode and writing ‘C’ on the cell (textbox), Cancel_Click is triggered. I have no code whatsoever for the datagrid. I hope you can I try it out. Thanks.

  72. Carter,

    Do you have an email address that I can follow up offline with you?  I would like to take a look at the code for your issue.

  73. Carter says:

    Hi Vincent,

    Thanks for having the time to help me. But it suddenly worked now. What I did was, in Expression Blend, I deleted the DataGrid in the Window, then I added a new DataGrid (same name, default properties) and now when I press ‘C’, it goes into edit mode. Don’t know what happened. I did install toolkit v1 but I doubt that’s got anything to do with it. Maybe. Thanks anyway!

  74. Carter says:

    Me again Vincent,

    I thought the problem was gone but apparently, it wasn’t. I’ve included the whole code I used. This Window only contains a DataGrid (no properties changed except width, height, and position-related properties) and a button (IsCancel = False, Content = _Cancel). If you want to reproduce the behavior, upon loading, single-click the first cell and type ‘C’. The window will close and if you try to put a breakpoint in btnCancel, you will see that it is triggered upon pressing ‘C’. BTW, my email is bongbong_23@yahoo.com. Thanks a lot!

    using System;

    using System.IO;

    using System.Net;

    using System.Windows;

    using System.Windows.Controls;

    using System.Windows.Data;

    using System.Windows.Media;

    using System.Windows.Media.Animation;

    using System.Windows.Navigation;

    using System.Collections.ObjectModel;

    using Microsoft.Windows.Controls;

    namespace UntitledProject1

    {

    public partial class Window1

    {

           private ObservableCollection<Employee> _EmployeeList = new ObservableCollection<Employee>();

           //

           //

           //

    public Window1()

    {

    this.InitializeComponent();

    // Insert code required on object creation below this point.

               this.Loaded += new RoutedEventHandler(Window1_Loaded);

               this.btnCancel.Click += new RoutedEventHandler(btnCancel_Click);

    }

           // Cancel’s Content property is _Cancel.

           private void btnCancel_Click(object sender, RoutedEventArgs e)

           {

               this.Close();

           }

           private void Window1_Loaded(object sender, RoutedEventArgs e)

           {            

               dgrd.AutoGenerateColumns = false;

               // Columns.

               DataGridTextColumn colFirstName = new DataGridTextColumn();

               Binding b = new Binding("FirstName");

               b.Mode = BindingMode.TwoWay;

               colFirstName.Binding = b;

               colFirstName.Width = new DataGridLength(100, DataGridLengthUnitType.Star);

               colFirstName.CanUserSort = false;

               colFirstName.Header = "First Name";

               dgrd.Columns.Add(colFirstName);

               DataGridTextColumn colMiddleName = new DataGridTextColumn();

               b = new Binding("MiddleName");

               b.Mode = BindingMode.TwoWay;

               colMiddleName.Binding = b;

               colMiddleName.Width = new DataGridLength(200, DataGridLengthUnitType.Star);

               colMiddleName.CanUserSort = false;

               colMiddleName.Header = "Middle Name";

               dgrd.Columns.Add(colMiddleName);

               DataGridTextColumn colLastName = new DataGridTextColumn();

               b = new Binding("LastName");

               b.Mode = BindingMode.TwoWay;

               colLastName.Binding = b;

               colLastName.Width = new DataGridLength(50, DataGridLengthUnitType.Star);

               colLastName.CanUserSort = false;

               colLastName.Header = "Last Name";

               dgrd.Columns.Add(colLastName);

               dgrd.ItemsSource = _EmployeeList;

           }

           private class Employee

           {

               public string FirstName { get; set; }

               public string MiddleName { get; set; }

               public string LastName { get; set; }

           }

    }

    }

  75. BRanck says:

    Could you point me to any write up on the changes between the RTM and V1 of:

    In the RTM it was  – DataFieldBinding

    In the RTM it was –  DataGridRowsPresenter

    In the RTM it was – DataGridColumnHeader

    Each of these RTM Names break my code when using version 1, so it would help if you could point me to the right place to start reading about the changes.

  76. David Anderson says:

    Hi Vincent!

    I need to generate group summaries like sums and averages. Can you point me in the right direction?

    Thanks for all your hard work!

  77. Femi says:

    Could you pls show an xample of using linq to bind a data to the SP1 Datagrid?

    i cant seem to find any example whatsoever..

    It seems all the articles assume that we all know how databind but its not so.

    thxs

  78. Femi,

    The sample on this post, http://blogs.msdn.com/vinsibal/archive/2008/10/22/wpf-datagrid-and-the-wpftoolkit-have-released.aspx, shows an example of binding using linq to sql.  

    This article here, http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx, also talks about this as well.

  79. John says:

    I need to customize my cell value in WPF. Previously I have done the same by inheriting DataGridView – DataGridViewTextBoxCell and override Paint method.  

    Do we have an equivalent for the same in WPF DataGrid?

  80. John,

    In the WPF DataGrid you can customize the cell by using either different templates through the DataGridTemplateColumn or changing the style of one of the existing stock columns.  You can learn more about it here, http://blogs.msdn.com/vinsibal/archive/2008/08/19/wpf-datagrid-stock-and-template-columns.aspx.

  81. Abhishek Datta Gupta says:

    Hi Vincent,

        I am working on a typical big project in VB 2005. Recently, we decided to migrate to 2008 version using WPF to create a new UI. I am using WPF datagrid from the WPF toolkit.

        However, I am NOT able to dynamically add row values in the datagrid. Since I can’t attach any sample code.I will describe the same.

        Plz create a WPF app. Add 6 textboxes, a button and the WPF datagrid. I the code view I have something like this:

    ‘%%%%CODE STARTS%%%%%%%%%%

       Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click

           Dim colcount As Integer = 3         ‘ values hardcoded here, as there are 3 textboxes for column entry

           Dim rowcount As Integer = 1         ‘ values hardcoded here

           Dim TD_Param_Column(0, 2) As String

           Dim TD_Param_Columnname

           ReDim TD_Param_Columnname(colcount – 1)

           ‘For l = 0 To colcount – 1

           TD_Param_Columnname(0) = TextBox1.Text

           TD_Param_Columnname(1) = TextBox2.Text

           TD_Param_Columnname(2) = TextBox3.Text

           ‘ Next

           TD_Param_Column(0, 0) = TextBox4.Text

           TD_Param_Column(0, 1) = TextBox5.Text

           TD_Param_Column(0, 2) = TextBox6.Text

           ‘===========================================

           ‘Adding the columns to the Datagridview1 : 2005 version

           ‘For l = 1 To colcount – 2

           ‘    Me.DataGridView3.Columns.Add(("Column" & l), TD_Param_Columnname(l – 1))

           ‘Next

           ‘Adding the columns to the Datagrid1 : 2008 version

           For l = 0 To colcount – 1

               Try

                   Dim dgtc As Microsoft.Windows.Controls.DataGridTextColumn = New Microsoft.Windows.Controls.DataGridTextColumn()

                   dgtc.Header = TD_Param_Columnname(l)

                   Me.DataGrid1.Columns.Add(dgtc)

               Catch

               End Try

           Next

           ‘===========================================

           ‘===========================================

           ‘Adding the rows to the Datagrid1 : 2005 version

           ‘Dim l As Integer

           ”Writing the the test datas in Old Variant grid

           ‘For k = 1 To rowcount – 1

           ‘    l = 1

           ‘    For g = colcount – 2 To 1 Step -1

           ‘        Try

           ‘            Me.DataGridview3.Rows(k).Cells(l).Value() = TD_Param_Column(k, g)

           ‘            l = l + 1

           ‘        Catch

           ‘        End Try

           ‘    Next

           ‘Next

           ‘Adding the rows to the Datagrid1 : 2008 version  NOT WORKING !!!!

           For l = 0 To colcount – 1

               Try

                   Dim dgtr As Microsoft.Windows.Controls.DataGridRow = New Microsoft.Windows.Controls.DataGridRow()

                   dgtr.SetValue(DataGrid1.Items(0), TD_Param_Column(0, l))

                   Me.DataGrid1.Items.Add(dgtr)

               Catch

               End Try

           Next

           ‘===========================================

       End Sub

    ‘%%%%% CODE ENDS%%%%%%%

    Please tell me how to add row values dynamically in the above code.

    Thanks and Regards,

    Abhishek

  82. Arun Nair says:

    Hi

    I am trying to setup two-way binding in the datagrid, but some how it does not seem to work.  I am able to change the value in the cell, but as soon as the cell loses focus, the value in the cell reverts back to what was there before I made the change.  The DataGrid is setup like this:

           <dg:DataGrid  Grid.Row="2" x:Name="melodyListView" ItemsSource="{StaticResource melody}" AutoGenerateColumns="False" HorizontalAlignment="Right" Width="224" Margin="0,6,0,0">

               <dg:DataGrid.Columns>

                   <dg:DataGridTextColumn Binding="{Binding Name, Mode=TwoWay}" Header="Name" CanUserSort="False" />

                   <dg:DataGridTextColumn Binding="{Binding Duration, Mode=TwoWay, Converter={StaticResource durationConverter}}" CanUserSort="False" Header="Duration" />

                   <dg:DataGridTextColumn Binding="{Binding Volume, Mode=TwoWay, Converter={StaticResource volumeConverter}}" CanUserSort="False" Header="Volume" />

               </dg:DataGrid.Columns>

           </dg:DataGrid>

    In the code the binding is setup:

    melody = new Melody();

               melodyListView.DataContext = melody;

               Binding b = new Binding();

               melodyListView.SetBinding(Microsoft.Windows.Controls.DataGrid.ItemsSourceProperty, b);

           }

    Any idea what am I missing here?

  83. Arun Nair,

    Does your melody class implement IEditableObject?

  84. Sriram says:

    Hi,

    I want to Copy the contents of the datagrid on a button click event. If i try to set the Application Command.Copy in my button, it is getting disabled always.

    Can you help me to acheive this clipboard copy of datagrid by button click.

    Thanks,

    Sriram

  85. Sriram,

    If you want to do it in the click event you can do something like this:

    private void Button_Click(object sender, RoutedEventArgs e)

           {

               this.MyDataGrid.SelectAll();

               ApplicationCommands.Copy.Execute(null, this.MyDataGrid);

           }

  86. CHARLEY SHENG says:

    Vinsibal,

    how could i get the datagridcell from datagridcellinfo object?

    thanks,

    charley

  87. Gary says:

    I am trying to iterate through all checked rows on the DataGrid. How is this done?

  88. Akash says:

    Hi vinsibal,

    I want to map A CSV file on to WPF datagrid. How can I do that? Thanks in advance.

Skip to main content