Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Silverlight
Silverlight 2
DataGrid Class

  Switch on low bandwidth view
.NET Framework Class Library for Silverlight
DataGrid Class

Displays data in a customizable grid.

Namespace:  System.Windows.Controls
Assembly:  System.Windows.Controls.Data (in System.Windows.Controls.Data.dll)
Visual Basic (Declaration)
<TemplatePartAttribute(Name := "ColumnHeadersPresenter", Type := GetType(DataGridColumnHeadersPresenter))> _
<TemplatePartAttribute(Name := "HorizontalScrollbar", Type := GetType(ScrollBar))> _
<TemplatePartAttribute(Name := "VerticalScrollbar", Type := GetType(ScrollBar))> _
<TemplatePartAttribute(Name := "RowsPresenter", Type := GetType(DataGridRowsPresenter))> _
<TemplatePartAttribute(Name := "FrozenColumnScrollBarSpacer", Type := GetType(FrameworkElement))> _
Public Class DataGrid _
    Inherits Control
Visual Basic (Usage)
Dim instance As DataGrid
C#
[TemplatePartAttribute(Name = "ColumnHeadersPresenter", Type = typeof(DataGridColumnHeadersPresenter))]
[TemplatePartAttribute(Name = "HorizontalScrollbar", Type = typeof(ScrollBar))]
[TemplatePartAttribute(Name = "VerticalScrollbar", Type = typeof(ScrollBar))]
[TemplatePartAttribute(Name = "RowsPresenter", Type = typeof(DataGridRowsPresenter))]
[TemplatePartAttribute(Name = "FrozenColumnScrollBarSpacer", Type = typeof(FrameworkElement))]
public class DataGrid : Control
XAML Object Element Usage
<swcd:DataGrid .../>

XAML Values

swcd:

A prefix that is defined to map the XML namespace for the System.Windows.Controls.Data assembly and the System.Windows.Controls CLR namespace.

The DataGrid control provides a flexible way to display a collection of data in rows and columns. The built-in column types include a text box column, a check box column, and a template column for hosting custom content. The built-in row type includes a drop-down details section that you can use to display additional content below the cell values.

To bind the DataGrid to data, set the ItemsSource property to an IEnumerable implementation. Each row in the data grid is bound to an object in the data source, and each column in the data grid is bound to a property of the data object. In order for the DataGrid user interface to update automatically when items are added to or removed from the source data, the DataGrid must be bound to a collection that implements INotifyCollectionChanged, such as an ObservableCollection<(Of <(T>)>).

By default, the DataGrid control generates columns automatically when you set the ItemsSource property. The generated columns are of type DataGridCheckBoxColumn for bound Boolean (and nullable Boolean) properties, and of type DataGridTextColumn for all other properties. If a property does not have a String or numeric value type, the generated text box columns are read-only and display the data object's ToString value.

You can prevent automatic column generation by setting the AutoGenerateColumns property to false. This is useful if you want to create and configure all columns explicitly. Alternatively, you can let the data grid generate columns, but handle the AutoGeneratingColumn event to customize columns after creation. To rearrange the display order of the columns, you can set the DisplayIndex property for individual columns.

Regardless of whether you generate columns, you can use the DataGrid..::.Columns collection to programmatically add, insert, remove, and change any columns in the control at run time. Alternatively, you can specify columns in XAML, in which case you should set AutoGenerateColumns to false. Creating your own columns enables you to use additional column types, such as the DataGridTemplateColumn type or custom column types. The DataGridTemplateColumn type provides an easy way to create a simple custom column. The CellTemplate and CellEditingTemplate properties enable you to specify content templates for both display and editing modes.

The DataGrid control supports common table formatting options, such as alternating row backgrounds and the ability to show or hide headers, grid lines, and scroll bars. Additionally, the control provides several style and template properties that you can use to completely change the appearance of the control and its rows, columns, headers, and cells.

To customize DataGrid behavior, you can handle events for selection change, cell editing, and column re-ordering. The DataGrid also exposes several events for row recycling that you can handle to further customize rows.

For information about tasks you can accomplish with the DataGrid control, see DataGrid.

NoteNote:

The Silverlight DataGrid control is only available as part of the libraries in the Silverlight Software Development Kit (SDK). For more information, see the Silverlight Tools.

XAML Usage for Classes Derived from DataGrid

If you define a class that derives from DataGrid, the class can be used as an object element in XAML, and all of the inherited properties and events that show a XAML usage in the reference for the DataGrid members can have the same XAML usage for the derived class. However, the object element itself must have a different prefix mapping than the swcd: mapping shown in the usages, because the derived class comes from an assembly and namespace that you create and define. You must define your own prefix mapping to an XML namespace to use the class as an object element in XAML.

The following code example creates a page with several DataGrid controls configured in a variety of ways.

<UserControl x:Class="DataGridSnippets.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     
    xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
    Width="500" Height="Auto">
    <ScrollViewer VerticalScrollBarVisibility="Auto" BorderThickness="0">
    <StackPanel Margin="10,10,10,10">

        <TextBlock Text="DataGrid Demonstration" Margin="0,20,10,20"
            FontFamily="Verdana" FontSize="18" FontWeight="Bold"
            Foreground="#FF5C9AC9" />

        <TextBlock Text="DataGrid with autogenerated columns:"/>
        <data:DataGrid x:Name="dataGrid1" 
            Height="140" Margin="0,5,0,10"
            AutoGenerateColumns="True" />            

        <TextBlock Text="DataGrid with row details sections:"/>
        <data:DataGrid x:Name="dataGrid3" 
            Height="140" Margin="0,5,0,10"
            RowDetailsVisibilityMode="VisibleWhenSelected" >            
            <data:DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontSize="12" Text="Address: " />
                        <TextBlock FontSize="12" Text="{Binding Address}"/>
                    </StackPanel>
                </DataTemplate>
            </data:DataGrid.RowDetailsTemplate>                
        </data:DataGrid>

        <TextBlock Text="DataGrid with configured columns:"/>
        <data:DataGrid x:Name="dataGrid4" 
            Height="160" Margin="0,5,0,10" 
            RowHeight="40" AutoGenerateColumns="False" >    
            <data:DataGrid.Columns>
                <data:DataGridTextColumn 
                    Header="First Name" 
                    Width="SizeToHeader"
                    Binding="{Binding FirstName}" 
                    FontSize="20" />
                <data:DataGridTextColumn 
                    Header="Last Name" 
                    Width="SizeToCells"
                    Binding="{Binding LastName}" 
                    FontSize="20" />
                <data:DataGridTextColumn 
                    Header="Address"
                    Width="150"
                    Binding="{Binding Address}" >
                    <data:DataGridTextColumn.ElementStyle>
                        <Style TargetType="TextBlock">
                            <Setter Property="TextWrapping" Value="Wrap"/>
                        </Style>
                    </data:DataGridTextColumn.ElementStyle>
                    <data:DataGridTextColumn.EditingElementStyle>
                        <Style TargetType="TextBox">
                            <Setter Property="Foreground" Value="Blue"/>
                        </Style>
                    </data:DataGridTextColumn.EditingElementStyle>
                </data:DataGridTextColumn>
                <data:DataGridCheckBoxColumn 
                    Header="New?" 
                    Width="40"
                    Binding="{Binding IsNew}" />
                <data:DataGridCheckBoxColumn 
                    Header="Subscribed?" 
                    Width="Auto"
                    Binding="{Binding IsSubscribed}" 
                    IsThreeState="True" />
            </data:DataGrid.Columns>
        </data:DataGrid>

        <TextBlock Text="DataGrid with template column and custom alternating row backgrounds:"/>
        <data:DataGrid x:Name="dataGrid5" 
            Height="125" Margin="0,5,0,10"
            AutoGenerateColumns="False"
            RowBackground="Azure"
            AlternatingRowBackground="LightSteelBlue">
            <data:DataGrid.Columns>
                <!-- Name Column -->
                <data:DataGridTemplateColumn Header="Name">
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Padding="5,0,5,0"
                                    Text="{Binding FirstName}"/>
                                <TextBlock Text="{Binding LastName}"/>
                            </StackPanel>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate> 
                    <data:DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBox Padding="5,0,5,0"
                                    Text="{Binding FirstName}"/>
                                <TextBox Text="{Binding LastName}"/>
                            </StackPanel>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellEditingTemplate> 
                </data:DataGridTemplateColumn>              
                <!-- Address Column -->
                <data:DataGridTextColumn
                    Header="Address" Width="300"
                    Binding="{Binding Address}" />
            </data:DataGrid.Columns>
        </data:DataGrid>
    </StackPanel>
    </ScrollViewer>
</UserControl>

Visual Basic
Partial Public Class Page
    Inherits UserControl

    Public Sub New()
        InitializeComponent()

        dataGrid1.ItemsSource = Customer.GetSampleCustomerList()
        dataGrid3.ItemsSource = Customer.GetSampleCustomerList()
        dataGrid4.ItemsSource = Customer.GetSampleCustomerList()
        dataGrid5.ItemsSource = Customer.GetSampleCustomerList()
    End Sub

End Class

Public Class Customer
    Dim m_FirstName As String
    Dim m_LastName As String
    Dim m_Address As String
    Dim m_IsNew As Boolean
    Dim m_IsSubscribed As Boolean?

    Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal address As String, ByVal isNew As Boolean, ByVal isSubscribed As Boolean?)
        Me.FirstName = firstName
        Me.LastName = lastName
        Me.Address = address
        Me.IsNew = isNew
        Me.IsSubscribed = isSubscribed
    End Sub

    Property FirstName() As String
        Get
            Return m_FirstName
        End Get
        Set(ByVal value As String)
            m_FirstName = value
        End Set
    End Property

    Property LastName() As String
        Get
            Return m_LastName
        End Get
        Set(ByVal value As String)
            m_LastName = value
        End Set
    End Property

    Property Address() As String
        Get
            Return m_Address
        End Get
        Set(ByVal value As String)
            m_Address = value
        End Set
    End Property

    Property IsNew() As Boolean
        Get
            Return m_IsNew
        End Get
        Set(ByVal value As Boolean)
            m_IsNew = value
        End Set
    End Property

    Property IsSubscribed() As Boolean?
        Get
            Return m_IsSubscribed
        End Get
        Set(ByVal value As Boolean?)
            m_IsSubscribed = value
        End Set
    End Property

    Public Shared Function GetSampleCustomerList() As List(Of Customer)
        Return New List(Of Customer)(New Customer() _
               {New Customer("A.", "Zero", "12 North Third Street, Apartment 45", False, True), _
                New Customer("B.", "One", "34 West Fifth Street, Apartment 67", False, False), _
                New Customer("C.", "Two", "56 East Seventh Street, Apartment 89", True, Nothing), _
                New Customer("D.", "Three", "78 South Ninth Street, Apartment 10", True, True)})
    End Function
End Class

C#
using System;
using System.Collections.Generic;
using System.Windows.Controls;

namespace DataGridSnippets
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            // Set the ItemsSource to autogenerate the columns.
            dataGrid1.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid3.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid4.ItemsSource = Customer.GetSampleCustomerList();
            dataGrid5.ItemsSource = Customer.GetSampleCustomerList();
        }
    }

    public class Customer
    {
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Address { get; set; }
        public Boolean IsNew { get; set; }

        // A null value for IsSubscribed can indicate 
        // "no preference" or "no response".
        public Boolean? IsSubscribed { get; set; }

        public Customer(String firstName, String lastName, 
            String address, Boolean isNew, Boolean? isSubscribed)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Address = address;
            this.IsNew = isNew; 
            this.IsSubscribed = isSubscribed;
        }

        public static List<Customer> GetSampleCustomerList()
        {
            return new List<Customer>(new Customer[4] {
                new Customer("A.", "Zero", 
                    "12 North Third Street, Apartment 45", 
                    false, true), 
                new Customer("B.", "One", 
                    "34 West Fifth Street, Apartment 67", 
                    false, false),
                new Customer("C.", "Two", 
                    "56 East Seventh Street, Apartment 89", 
                    true, null),
                new Customer("D.", "Three", 
                    "78 South Ninth Street, Apartment 10", 
                    true, true)
            });
        }
    }
}

Run this sample.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker