Home  separator  Controls  separator  DataGrid
Bookmark and Share Share...    Subscribe to this feed Feed   About Christian Moser  


WPF DataGrid Control

Introduction

Since .NET 4.0, Microsoft is shipping a DataGrid control that provides all the basic functionality needed, like:


Basic usage: Auto generate columns

To show a basic data grid , just drop a DataGrid control to your view and bind the ItemsSource to a collection of data objects and you're done. The DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the public properties of your data objects. It generates the following types of columns:

  • TextBox columns for string values
  • CheckBox columns for boolean values
  • ComboBox columns for enumerable values
  • Hyperlink columns for Uri values

 
<DataGrid ItemsSource="{Binding Customers}" />
 
 

Manually define columns

Alternatively you can define your columns manually by setting the AutoGenerateColumns property to False. In this case you have to define the columns in the Columns collection of the data grid. You have the following types of columns available:

  • DataGridCheckBoxColumn for boolean values
  • DataGridComboBoxColumn for enumerable values
  • DataGridHyperlinkColumn for Uri values
  • DataGridTemplateColumn to show any types of data by defining your own cell template
  • DataGridTextColumn to show text values

 
<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding Image}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
 
 

Selection

The data grid includes a variety of selection modes. They are configured by the SelectionMode and SelectionUnit property.

  • The SelectionMode can be set to Single or Extended to define if one or multiple units can be selected simultaneously.
  • The SelectionUnit defines the scope of one selection unit. It can be set to Cell, CellAndRowHeader and FullRow.
 
<DataGrid ItemsSource="{Binding Customers}" 
          SelectionMode="Extended" SelectionUnit="Cell" />
 
 

Column sorting, reordering and resizing

The data grid provides features to sort, reorder and resize columns. They can be enabled or disabled by the following properties:

  • CanUserReorderColumns enables or disables column re-ordering
  • CanUserResizeColumns enables or disables column resizing
  • CanUserResizeRows enables or disables row resizing
  • CanUserSortColumns enables or disables column sorting

 
<DataGrid ItemsSource="{Binding Customers}" 
          CanUserReorderColumns="True" CanUserResizeColumns="True" 
          CanUserResizeRows="False" CanUserSortColumns="True"/>
 
 

Grouping

The data grid also supports grouping. To enable grouping you have to define a CollectionView that contains to least one GroupDescription that defines the criterias how to group.

 
Customers = new ListCollectionView(_customers);
Customers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));
 
 

Second thing you need to do is defining a template how the groups should look like. You can do this by setting the GroupStyle to something like the following snippet.

 
<DataGrid ItemsSource="{Binding GroupedCustomers}">
    <DataGrid.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Name}" />
                    </StackPanel>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
            <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type GroupItem}">
                                <Expander>
                                    <Expander.Header>
                                        <StackPanel Orientation="Horizontal">
                                          <TextBlock Text="{Binding Path=Name}" />
                                          <TextBlock Text="{Binding Path=ItemCount}"/>
                                          <TextBlock Text="Items"/>
                                        </StackPanel>
                                    </Expander.Header>
                                    <ItemsPresenter />
                                </Expander>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </GroupStyle.ContainerStyle>
        </GroupStyle>
    </DataGrid.GroupStyle>
</DataGrid>
 
 

Row Details

The data grid provides a feature that shows a detail panel for a selected row. It can be enabled by setting a DataTemplate to the RowDetailsTemplate property. The data template gets the object that is bound to this row passed by the DataContext and can bind to it.

 
<DataGrid ItemsSource="{Binding Customers}">
    <DataGrid.Columns>
    <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
    </DataGrid.Columns>
    <DataGrid.RowDetailsTemplate>
        <DataTemplate>
            <Image Height="100" Source="{Binding Image}" />
        </DataTemplate>
    </DataGrid.RowDetailsTemplate>
</DataGrid>
 
 

Row Details depending on the type of data

You can specify a RowDetailsTemplateSelector that selects a data template according to the type or data that this row contains. To do this, create a type that derives from DataTemplateSelector and override the SelectTemplate method. In the items argument you get the data and you can determine which data template to display. Return an instance of that data template as return value.

 
public class GenderTemplateSelector : DataTemplateSelector
{
    public DataTemplate MaleTemplate { get; set; }
    public DataTemplate FemaleTemplate { get; set; }
 
    public override DataTemplate SelectTemplate(object item, 
                  DependencyObject container)
    {
        var customer = item as Customer;
        if (customer == null)
            return base.SelectTemplate(item, container);
 
        if( customer.Gender == Gender.Male)
        {
            return MaleTemplate;
        }
        return FemaleTemplate;
    }
}
 
 

 
<l:GenderTemplateSelector x:Key="genderTemplateSelector">
    <l:GenderTemplateSelector.MaleTemplate>
        <DataTemplate>
            <Grid Background="LightBlue">
                <Image Source="{Binding Image}" Width="50" />
            </Grid>
        </DataTemplate>
    </l:GenderTemplateSelector.MaleTemplate>
    <l:GenderTemplateSelector.FemaleTemplate>
        <DataTemplate>
            <Grid Background="Salmon">
                <Image Source="{Binding Image}" Width="50" />
            </Grid>
        </DataTemplate>
    </l:GenderTemplateSelector.FemaleTemplate>
</l:GenderTemplateSelector>
 
<DataGrid ItemsSource="{Binding Customers}" 
          RowDetailsTemplateSelector="{StaticResource genderTemplateSelector}" />
 
 

Alternating BackgroundBrush

You can define a an AlternatingRowBackground that is applied every even row. You can additionally specify an AlternationCount if you only want to ink every every n-th data row.

 
<DataGrid ItemsSource="{Binding Customers}" 
          AlternatingRowBackground="Gainsboro"  AlternationCount="2"/>
 
 

Frozen Columns

The data grid also supports the feature to freeze columns. That means they stay visible while you scoll horizontally through all columns. This is a useful feature to keep a referencing column like an ID or a name always visible to keep your orientation while scrolling.

To freeze a numer of columns just set the FrozenColumnCount property to the number of columns you want to freeze.

 
<DataGrid ItemsSource="{Binding Customers}" FrozenColumnCount="2"  />
 
 

Headers visbility

You can control the visibility of row and column headers by setting the HeadersVisibility property to either None,Row,Column or All

 
<DataGrid ItemsSource="{Binding Customers}" HeadersVisibility="None" />
 
 

How to template autogenerated columns

If you want to autogenerate columns using AutoGenerateColumns="True", you cannot use CellTemplates, because the DataGrid autogenerates either a text, combo, hyperlink or checkbox column, but none of these are templateable. A simple workaround is to hook into the autogeneration, cancel it and always create a DataGridTemplateColumn. The following snippet shows the idea (the code is just a draft):

 
public class MyDataGrid : DataGrid
{
 
    public DataTemplateSelector CellTemplateSelector
    {
        get { return (DataTemplateSelector)GetValue(CellTemplateSelectorProperty); }
        set { SetValue(CellTemplateSelectorProperty, value); }
    }
 
    public static readonly DependencyProperty CellTemplateSelectorProperty =
        DependencyProperty.Register("Selector", typeof(DataTemplateSelector), typeof(MyDataGrid), 
        new FrameworkPropertyMetadata(null));
 
 
 
    protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
    {
        e.Cancel = true;
        Columns.Add(new DataGridTemplateColumn
            {
                Header = e.Column.Header, 
                CellTemplateSelector = CellTemplateSelector
            });
    }
}
 
 
 
<l:MyDataGrid ItemsSource="{Binding}" 
              AutoGenerateColumns="True" 
              CellTemplateSelector="{StaticResource templateSelector}" />
 
 




Last modified: 2011-04-19 08:55:41
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments
Hari
Commented on 9.March 2010
Hi,

Really Nice Article. Given good insight into the .NET 4.0 DataGrid.
Keep Posting good stuff...

Many Thanks,
Hari.
Ravi
Commented on 9.March 2010
Hi, This is really AWESOME...... keep rocking
Anoop
Commented on 10.March 2010
Great Site ! I love this site !! Thank you very much
Yuan
Commented on 16.March 2010
Great! Many Thanks.
Mahendra Wagh
Commented on 17.March 2010
I can learn many more from this article, Its really good.
Dhiva
Commented on 18.March 2010
Great Articlas
ghi hooil
Commented on 25.March 2010
goood test
kenntrix
Commented on 29.March 2010
great post. thanks helps a lot.

visit http://www.kenntrix.info
Munna
Commented on 31.March 2010
Really Helpful information.
Mahender
Commented on 13.April 2010
Great Realy Helpfull
Adeel
Commented on 15.April 2010
Good post
Phillip
Commented on 16.April 2010
What's the best control/method to get similar functionality with .Net 3.5 where the Datagrid is not available?
lan
Commented on 19.April 2010
I like your site, neat architecture and useful artical, thanks:)
ram
Commented on 21.April 2010
good
YJ
Commented on 25.April 2010
Thanks for your kind post. always helpful
YJ
Commented on 25.April 2010
Hi Mosers, is it possible to display bitmap and text in single column of this control like ListView (for example: http://msdn.microsoft.com/en-us/library/bb613548.aspx)?
ichi
Commented on 26.April 2010
Wowwwww go DotNet! i love Microsoft Development. thsssbsbsbsb to the PHP Cake framework!
FlashHack
Commented on 26.April 2010
Hey Christian,
When I implement the DataGrid, whenever the DataContext is changed I loose my SortDescriptions. In essence, I cannot specify a default sort order for the grid and the user is forced to click a header in order to view the sorted data. Any suggestions as to what could I be doing wrong?
susmit singh
Commented on 30.April 2010
Great article much more helpful....
Shani
Commented on 30.April 2010
Great article. Its very helpfull....
kanna
Commented on 1.May 2010
this was good article keep rocking
Rosh
Commented on 3.May 2010
Hi, Can you please answer me how i change focus from one cell to another by code?
Anatoly
Commented on 3.May 2010
Hi. How can I display row with SelectedItem, which SelectedIndex i changed by code?
dataGrid1.SelectedIndex = 90;
And i want to display row with index = 90.
bahadur khan
Commented on 6.May 2010
HI,
I HAVE NEVER FOUND BEFORE IT SUCH SUCH GOOD MATERIAL ON WPF .
ONCE AGAIN THANKS IN ADVANCE
I ALSO REQUEST YOU TO UPLOAD VEDIO OF WPF TRAINING .

WITH REGARDS
BAHADUR KHAN
Alistair
Commented on 11.May 2010
Hi, Thankyou for such a useful example on how to use datagrids.
One thing I\'m still trying to work out is how to have comboboxes in one column with DIFFERENT items in them. Also to be able to dynamically change what the drop down items are dependent on the value in a different column.
Any help on this would be much appreciated.

Thanks
Alistair
Hiren solanki
Commented on 14.May 2010
my comment is classified as a span other wise i would have tell lots of to WPF newbies any body wants wpf video learning material link please mail me on hiren_it2008@yahoo.com
ramunz
Commented on 18.May 2010
so simple, so well explained, you read it on books and they talk and talk and talk ..and so forth...wonder, do you have an advise for all those authors on how to write a very good article/book like your articles. Here you read and you fill like you learn a lot. Keep up the good work. THANKS!!!
eng.ghost
Commented on 23.May 2010
so fantastic
nice to learn WPF from this site
thank u man for ur efforts
u have made a gr8 job
rjangid
Commented on 27.May 2010
thanks to visit this site .... here lot to learn
indiagems
Commented on 27.May 2010
visit www.indiagems.com to purchase jewelery
sebas
Commented on 27.May 2010
In the Text={Binding Path=Name}
What is Name in this context?What other properties are there besides Name and ItemCount, IS there a built-in summation available?
Amol
Commented on 2.June 2010
Nice tutorial. Forward me implementation details on email id specified above
Amol
Commented on 2.June 2010
Nice tutorial. Forward me implementation details on email id specified above
Subil
Commented on 3.June 2010
Can you please post the full code for grouping.The result should be like in the picture you given for grouping.
Shajahan
Commented on 4.June 2010
Great Nice to learn WPF from This Site Thanks man for Your Efforts....................
Shajahan
Commented on 4.June 2010
Hi How Can i Show the Details for The Selected Row in that Row Expanding of the Gidview
Declan
Commented on 17.June 2010
Great article, just what I needed.
One question though, Is there a 'DataGridDateTimePickerColumn'? Or would I have to write one myself?
Declan
Commented on 17.June 2010
Great article, just what I needed.
One question though, Is there a 'DataGridDateTimePickerColumn'? Or would I have to write one myself?
Anthony Wieser
Commented on 18.June 2010
Just out of curiousity, why doesn't the GenderTemplateSelector change when you change the sex of an entry?
Chodu
Commented on 20.June 2010
the example has build errors! kahan se maru ise so that it runs???????
Raghav
Commented on 22.June 2010
Very!!! Very!!! helpful.
Amit Paul...
Commented on 29.June 2010
From my point of view this website would one day be a leading WPF tutorial site (like w3schools.com for web technologies) with numerous articles organized in an easy to navigate way. Thank you thousand times for your approach.
Hiren Solanki
Commented on 2.July 2010
Hello Mr.Chodu You just go and fuck the things..
Dont roam aroung my site.. we r believing it as Religion and you are just fucking off
Sans
Commented on 2.July 2010
Is it Possible to show the empty rows ??
venkat
Commented on 4.July 2010
the tutorial is really good.i am new to WPF and trying to understand the things.can anyone tell me how should i follow the order of tags?i.e. in Grouping the following are used:<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
i want to know how to follow the order.if possible cn anyone gv me link to the site?i am new to WPF...
Gaurav Dixit
Commented on 5.July 2010
Very nice article for beginners.....
Ali
Commented on 7.July 2010
Hello,
Thanks a lot...
God bless upon u for this article. U hv written a very good article and a useful too. Such tutorials are needed for newer as well as experienced because of technology changed.
I need Globalization and Localization in WPF (Desktop) article.

Please assist me....

Again Thanks a lot ...
Jeumelled
Commented on 7.July 2010
Could you please add information about the MultiBinding , especially on a column of a DataGrid
Rama
Commented on 8.July 2010
Very nice article. My requirement is how can I get objects for controls in DataTemplate column in code window. I added two button template column in datagrid and I want get objects of those buttons. Please assist me... Thanks
Rama
Commented on 8.July 2010
Very nice article. My requirement is how can I get objects for controls in DataTemplate column in code window. I added two button template column in datagrid and I want get objects of those buttons. Please assist me... Thanks
Tom
Commented on 8.July 2010
Nice one,
How to databind a List<Customer> to Grid.
Thanks.
Rajni Padhiyar
Commented on 12.July 2010
Nice Example

Thanks
Rajni Padhiyar
rajnicby.si@gmail.com
Avi
Commented on 12.July 2010
How to change the color of each row. different color for different row in WPF DataGrid ?
Avinash
Commented on 12.July 2010
How to change the color of each row. different color for different row in WPF DataGrid ?

Invinciblemachine@gmail.com
Avinash
Ziddan
Commented on 13.July 2010
In Simple Words, its very Helpful, my best regards to U and Ur Efforts
Greg
Commented on 21.July 2010
Christian, thanks for putting this series together. It looks like you have put in a bunch of hours. I have a suggestion - you might consider putting Next Prev buttons at the bottom (but above the comments) so users can flip through your pages w/o having to scroll back to the top. Just a thought. Thanks for the effort.
ReV
Commented on 24.July 2010
Hi Christian, is there any way to use something like lookup-editbox for grid with same specificity!
Marlon Manzo
Commented on 14.August 2010
your example was very intersting and your explanation are clear, but what i need with all the HyperLink that shows in the Datagrid is try to goes to another screen on the same window, the same thing if you are working on aspx using the command "redirect"
Kapil
Commented on 16.August 2010
First of all I like to thanks a lot for writing this good article. I want to add button against each row of the datagrid in wpf 4.0. Can you please suggest me how can I achieve this and I also want to take the row column 0 value on that row button click. Thanks in advance.
Rohit Kandhal
Commented on 17.August 2010
How can i group 2 rows depending on Sex , i mean if we have male entry in row then all male should be shown together with one column showing picture of male in all rows of mail. There would be only one image of Mail.
Kapil
Commented on 23.August 2010
How can we add footer in the data grid in framework 4.0.

Thanks & Regards
Kapil
kapilagarwal1@ymail.com
Majed
Commented on 31.August 2010
Well done. Thanks for this.
Ritchie
Commented on 9.September 2010
Great! Thanks.
Rashid
Commented on 23.September 2010
Though it has been said more elequently by others, this is a great article. Keep up the good work.
PVA
Commented on 29.September 2010
Hi. what about data binding whne you want a particular column in the grid to be able to accept drops from a treeview? I mean I want to drag a node from RadTreeView into a column of a RadGridView? Is that possible? If yes then what do I bind the column to? If not bind then which event handlers should I be using in the code behind to make the column accept the string data from the treenode? And if this is not possible then should I be using a DataGrid instead of a RadGridView?? Any reply/help/ would be appreciated.
Pissu Poosa
Commented on 5.October 2010
This is very helpful. thanks for Template selector example in this article. that save me lot of time. owsome
poornachandra
Commented on 14.October 2010
How to add a button the the datagrid column for less than 4.0 framework
mike
Commented on 14.October 2010
Thanks! This is the best DataGrid introduction I've found. Wish I had found it first before wasting time with the others.
lnluis
Commented on 20.October 2010
Hi, does this support hierarchical data for data grid>
nidhi
Commented on 21.October 2010
how to get rowheader mouse click event in datagrid control of wpf
AL
Commented on 21.October 2010
Nice toturial. Easy to undrstand and very useful
Ijaware...
Commented on 22.October 2010
Its a really nie tutorial but how to I allow the DataGridCells to be directly editable without binding to any observable collection.
Thanks in anticipation
Suhail...
Commented on 1.December 2010
Really Nice Article . It will be good if you provide zip file for it .
TMAN
Commented on 2.December 2010
How can edit the datagrid during runtime here is my xaml but I cannot update during runtime
<DataGrid Height="51" HorizontalAlignment="Left" Margin="176,99,0,0" Name="dtversionnumber" AutoGenerateColumns="True" VerticalAlignment="Top" Width="286" IsReadOnly="False" IsManipulationEnabled="True"/>
Gokuldas C.
Commented on 7.December 2010
Very nice article!. I want one of the header column to span over two columns. Can you please suggest how I can do this? I am able to customize the header using headertemplate.
Regards,
Gokul
Chetan
Commented on 7.December 2010
while using Datagrid i am getting an erro "Error 1 The tag 'DataGrid' does not exist in XML namespace 'http://schemas.microsoft.com/wpf/2008/toolkit'."
why this is so?
sivakanth
Commented on 13.December 2010
superb.
Nisarg Shah
Commented on 13.December 2010
Great article for beginners..Can you please tell me how to change cell color dynamically from the code??

Thanx in advance..
sri
Commented on 6.January 2011
Hi,
how could we enable/disable a row of a datagrid using MVVM??
RAM
Commented on 18.January 2011
Thanks. Whether we can extend WPF DataGrid?
Joy
Commented on 18.January 2011
Very Gud
Diego
Commented on 20.January 2011
Great site, thank you so much for spending your time to give us all this excelente content, tips, tricks and info about WPF.
ramani
Commented on 21.January 2011
its vry useful for me
tho
Commented on 21.January 2011
Can you send me all code? Thanks!
Bala
Commented on 24.January 2011
How to delete multiple columns from a datagrid in MVVM? I dont see SelectedItems property to bind?
GURENI...
Commented on 25.January 2011
congratulation,its good work.
I got a problems on data grid view,"I should write a message in separate form and when I send it,the first word of my message should be picked and listed in data grid view and loop should take position". May you please send to me visual basic 2005 code concerning this exercise.
Shankar
Commented on 27.January 2011
Thanks..,
Mohammad
Commented on 9.February 2011
Thanks Very good,
it is very helpfull for me
Wade
Commented on 10.February 2011
First off, I just want to say that I love your site and it has been way helpful.
My question though is...How do you get your content within a row to be centered and not hugging the top of the row?
Tejas Suthar
Commented on 12.February 2011
Thanks dear !! it's very usefull
Arun
Commented on 14.February 2011
Hi im still having problem in datagrid view in wpf can any one help me out. If possible mail me....
Arun
Commented on 14.February 2011
tell in 3.5 frame work
Raghu
Commented on 14.February 2011
good
GVERA
Commented on 15.February 2011
Hi, I followed your example on Grouping but, for some reason I cannot get a value from another property of my collection object: e.g <Textblock Text="{Binding ItemsCount}" /> This will not display a value. Any ideas?

Thanks.
jim
Commented on 16.February 2011
I don't get it. Why don't you just use Excel. It can show stuff in cells too.
slike9
Commented on 16.February 2011
Great! Thanks.
susmitha
Commented on 25.February 2011
its good,
if we go in deep, i want to highlight search key word in datagrid rows,can anyone help me
Clerks
Commented on 25.February 2011
Thanks. Really nice explanation
Clerks
Commented on 25.February 2011
Thanks. Really nice explanation
Pavan
Commented on 27.February 2011
Damn good article!
Halverny
Commented on 8.March 2011
Good Article. Anyway, it would be interesting to include something about cell content alignments so we may see lots of questions about it and very few good explainations.
Halverny
Commented on 8.March 2011
Good Article. Anyway, it would be interesting to include something about cell content alignments so we may see lots of questions about it and very few good explainations.
Martin
Commented on 8.March 2011
Hi, nice article, I got my headers working with the expander, however the property does not show up that I bind. If I add a manual textblock with some text, it works fine, but the bound property never shows. If set a breakpoint at the property thats bound, I see all calls made, but the text just doesnt show up.
Dorababu
Commented on 9.March 2011
Getting the following errors

The name 'InitializeComponent' does not exist in the current context

The name 'selectedCellsGrid' does not exist in the current context
sridharan
Commented on 16.March 2011
Article is good but how to use the datagrid in wpf application.I tried right click on toolbox and then select shoose items.But i can't add the gridview
Raja
Commented on 16.March 2011
Very useful tutorial ( and code included)
Vmqoz
Commented on 19.March 2011
Just wonderful! Thanks for this great article!
Sabbir Ahmed
Commented on 4.April 2011
It's great for me,Thanx
Mike
Commented on 4.April 2011
Thanx, a very good tut ! It was useful for me.
shaik
Commented on 6.April 2011
thanks
Khyati
Commented on 6.April 2011
Article is very good but if i enter some value to one cell and according to that want to change the next cell automatically then what will be the code?? help plz..thx
hai
Commented on 11.April 2011
good
hari kumar
Commented on 11.April 2011
Very userful for presenting data. What about data entry? WPF datagrid is an output of stupid design by peoplle who have no knowledge in basic data entry operations. Let me provide some of the many major bugs in wpf dtagrid using the following scenario.
datagrid.itemssource = dataset.table(0).defaultview (it has five columns)
if i enter a value to the first column, i will do the validation in the _CellEditEnding event. if the entered value is an existing value in the table(for example item code) i want to display the item description in the second column. If the item code is a non stock item, i should be able to modify the item description. The following are the bugs
If the second column is a datagridtext column, i can assing the description using the code datagrid.Columns(1).GetCellContent(e.Row).SetValue(TextBlock.TextProperty, &quot;This is a service item&quot;)
This code will not update the datasource(datarowview)!
So i assign the same value to the datasource using the code
Dim oDataRowView As DataRowView = e.Row.Item
odatarowview.item(1)=&quot;This is a service item&quot;)

If the column type is a datagridtemplatecolumn, you will not see any value in the second column until you double click on the second column!!!

If you agree with this and would like to see more bugs,please let me know







Brett Ryan
Commented on 15.April 2011
A welcomed addition to WPF. Though, could it be just me or does the default styling not match other WPF controls? Such as the default border for cells, they are defaulted to black. Personally a lot of WPF default styling doesn't match the native OS close enough, such as &quot;selected&quot; the default blue makes it look like it's from Win95.
vahid
Commented on 15.April 2011
it is very wonderful article but i have a question
i want to connect Access database to this control how can i do ?
Magda
Commented on 16.April 2011
Thanks for a good overview. I have one question/issue though. If I expand a group and then sort the grid, the group is collapsed. Any suggestion on a workaround so that the group maintains its state?
rama
Commented on 22.April 2011
hi,i have one question , how can we show arrow pointer in the left most column of the datagrid that to the selected row ,
Ashish
Commented on 23.April 2011
I t is very useful article but I have a question about datagrid control
i want to connect sql data base and display data as per database.....all data is displayed correctly but I want to change some properties of data grid such as column header style or header color then how it is possible. or forecolor of column header is different from cell value in datagrid please guide me
ganesh
Commented on 25.April 2011
informative
Radha
Commented on 26.April 2011
Best article
Tarannum Banu
Commented on 28.April 2011
very nice
Abhishek
Commented on 28.April 2011
Totally agree with Hari Kumar.

WPF might be good for designers ( which I don't believe myself, given the number of other tools present in the market), but it certainly not is very developer friendly.

Just getting a simple row index in the datagrid is very difficult. In short if its not about my job (&amp; curiosity) I would prefer working back on plain c# coz the development was lot faster than in wpf.
leif
Commented on 5.May 2011
does it support sub-headers?
Anto
Commented on 5.May 2011
Can you show more about image binding? I have table, bind with database, one of the column contain links to image file. I want to show the image instead of links in datagrid. How to do this?
Robert...
Commented on 11.May 2011
Agree with Hari Kumar! In LineOfBusiness applications are table-like-controls important. That's where you Add, Read, Update and Delete rows as we all know. I did, and I've runned in a lot of problems too trying to implement MVVM... e.g. DataGrid does not automaticaly refresh at the screen after a change in the viewmodel where it is bind to. I had to click on a sorted column to see that change.. In more posts on the internet I see that a lot of people who wants to publish knowledge stick with the trivial solutions and some way or the other don't touch the buggy, challenging parts and pitfalls. So Christian, why not extent this example with the really important features? It will surely add to the quality of your site. Thanks anyway.
TigerFab
Commented on 11.May 2011
Very good article ! Best one I have read.

But missing one point : Manage cells
1/ How change for example the color of one Cell by code ?
2/ How to know wich cell is selectionned by code ?

Thanks in advance !
GlenyR
Commented on 17.May 2011
Good Article, Can you show how to make a header filter?
Sreekumar
Commented on 24.May 2011
Good tutorial...
Shail
Commented on 26.May 2011
I need to create DataGrid dynamically in special way.
Let&acirc;s say I have two columns for grid 1) FieldName and 2) FieldValue which comes from database table.
Now one row data could have drop down, and other row could have text, and other row could have check box in Field Value. How do I create this kind of dataGrid dynamically? My biggest challenge is interacting with ColumnTemplate in individual cell level.

FieldName | Field Value
Sex | Radio Button to select Male or Female
Age | Drop Down Combo box to select age from 1 to 100
Name | Text box
is Employed | Check box to indicate whether employed or not

And another biggest challenge is I need to have Event on each FieldValue cell.
Event could be click, double click, Right mouse click, Enter etc.
Thank you
Shail
Anil Kumar...
Commented on 30.May 2011
Very very nice article explaining every aspect of the grid with a Good Code example. Eager to see some more articles on various controls..
patel...
Commented on 10.June 2011
please help i bind complete datagrid but how 2 work same as datagridview in window appllication
like dg.Rows.column.cell is not in datagrid and how 2 count totalrows like dg.rows.counthow 2 do in datagrid
patel...
Commented on 10.June 2011
which control equel datagridview in window app to wpf vs2010 reason i new in wpf vs 2010
bhagavan
Commented on 17.June 2011
awesome..i think its a knowledge of ocean
eshao
Commented on 5.July 2011
The datagrid in net4.0 is not good supported for mvvm.
THe datagrid don't have the &quot;command&quot; property like button,
eshao
Commented on 5.July 2011
if u use the datagrid wirh mvvm, u must do lot extra work that will hit u out off earth.
Srinivas
Commented on 7.July 2011
Superb, very Nice Article. It helped me a Lot. Thank U.
Dan
Commented on 13.July 2011
There is a great problem using grouping - when you call .Refresh() method of ListCollectionView, to update layout, it redraws all the datagrid and close all your groups.
May anybody answer how to refresh the data without those problems?
Dan
Commented on 13.July 2011
There is a great problem using grouping - when you call .Refresh() method of ListCollectionView, to update layout, it redraws all the datagrid and close all your groups.
May anybody answer how to refresh the data without those problems?
Dev
Commented on 21.July 2011
How did you made the View Source option disable on this page?
Luis
Commented on 23.July 2011
What should I do if I want another node directioned from the costumers class?
e.g.
public class Customer : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private Gender _gender;
private Uri _webSite;
private bool _newsletter;
private string _image;
private Phone _phones;// &lt;-------- this one
.
.
.
}
//where:

public class Phone:INotifyPropertyChanged
{
private int _homeNumber;
private int _celNumber;
private int _workNumber;
private int _faxNumber;
.
.
.
}

I want to display &quot;Phone&quot; values on a dataGrid, preferibly in a comboboxCell, I just want to display them, not edit them


thanks
Luis
Commented on 23.July 2011
What should I do if I want another node directioned from the costumers class?
e.g.
public class Customer : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private Gender _gender;
private Uri _webSite;
private bool _newsletter;
private string _image;
private Phone _phones;// &lt;-------- this one
.
.
.
}
//where:

public class Phone:INotifyPropertyChanged
{
private int _homeNumber;
private int _celNumber;
private int _workNumber;
private int _faxNumber;
.
.
.
}

I want to display &quot;Phone&quot; values on a dataGrid, preferibly in a comboboxCell, I just want to display them, not edit them


thanks
Derek
Commented on 27.July 2011
Is there anyway to get those check boxes to work with one click? The currently require two clicks to use. One to select the cell and one to click the check box.
Prabhat khare
Commented on 28.July 2011
I have a problem on paging,in which i want to show google type paging like 1 2 3 4...400 please suggest me,
Steve
Commented on 2.August 2011
Hari Kumar (and others) you are missing the point of the WPF datagrid, you don't access the rows/cells directly, the datagrid should be bound to a data set, changes made on the screen are reflected back to the data set and if you change the data set these changes are reflected on the screen.

It takes a bit of getting used to, but it's very powerfull once you understand how to use it.
Chirag
Commented on 10.August 2011
Would anyone know, how to make the grids look a bit more stylish as opposed to the normal windows 'blue' selection. I would like to add a bit more touch and feel
zahra
Commented on 20.August 2011
tanks alot.very good
Ruslan
Commented on 23.August 2011
I have a question about grouping. Let's say, I have a group style in resource dictionary, and I want to set datagrid group style to the group style from xaml. How can this be achieved?
Thank you in advance,
Ruslan
Ruslan
Commented on 23.August 2011
I have a question about grouping. Let's say, I have a group style in resource dictionary, and I want to set datagrid group style to the group style from xaml. How can this be achieved?
Thank you in advance,
Ruslan
Soby Mathew
Commented on 31.August 2011
very Nice Article.
Bhavneet
Commented on 12.September 2011
can u help me out?
actually problem is that i'm doing a project in WPF but when i drag grid on it then there is no property for autocolomn property or add colomn property.is the problem is of studio problem?
i'm using visual studio 2008..
detective jeera
Commented on 23.September 2011
Nice Article. Thanks for such a nice article.
Harikrishnan
Commented on 27.September 2011
Superb article.
How can I generate column dynamically from user preference column number values?
Ex: If I have 3 columns C1,C2,C3 and user chenges the order to C3,C1,C2 - I have to load the same way the user changed it the next time...
Can anyone Help!!!!

Name
E-Mail (optional)
Comment