How to: Add a DataGrid Control to a Page

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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. Since the DataGrid control is not a core control, it must be referenced properly before you can use it.

Adding a DataGrid Control by Dragging

The easiest way to add a DataGrid control and reference it properly is to drag it from the Toolbox to XAML view.

To add a DataGrid control by dragging in Visual Studio

  1. In your Silverlight project, open the All Silverlight Controls tab of the Toolbox.

  2. From the Toolbox, drag the DataGrid control to XAML or Design view.

    Visual Studio performs the following tasks automatically.

    • Adds a reference to the System.Windows.Controls.Data assembly.

    • In the <UserControl> start tag of the XAML page, adds an XML namespace declaration for the SDK namespace, as described in Prefixes and Mappings for Silverlight Libraries.

      xmlns:sdk="https://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

    • Adds the following XAML to your page if you drag the control to XAML view.

      <sdk:DataGrid />

      - or -

    • Adds the following XAML if you drag the control to Design view.

    <sdk:DataGrid AutoGenerateColumns="False" Height="100" Name="dataGrid2"
         Width="120" />
    

Adding a DataGrid Control Manually

To add a DataGrid control to your page manually, you must add a reference to the System.Windows.Controls.Data assembly and you must also map an XML namespace to the assembly.

To add a reference to the System.Windows.Controls.Data assembly in Visual Studio

  1. In your Silverlight project, click the Project menu, and then select Add Reference.

  2. In the .NET tab of the Add Reference dialog box, select System.Windows.Controls.Data.

  3. Click OK.

To add an XML namespace mapping

  1. Open MainPage.xaml.

  2. In the <UserControl> start tag, add the following markup.

    xmlns:sdk="https://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    

To add a DataGrid control in XAML

  1. Open MainPage.xaml.

  2. Add the following XAML to your page.

    <sdk:DataGrid></sdk:DataGrid>
    

Adding a DataGrid Control in Code

Once you have a reference to the System.Windows.Controls.Data assembly, you can also add a DataGrid in code. The following example creates a DataGrid named dataGrid1 and adds it to the LayoutRoot element of the page.

To add a DataGrid control in code

  1. Open MainPage.xaml.cs or MainPage.xaml.vb.

  2. Add the following code to your code behind page.

    DataGrid dataGrid1 = new DataGrid();
    LayoutRoot.Children.Add(dataGrid1);
    
    Dim dataGrid1 As New DataGrid
    LayoutRoot.Children.Add(dataGrid1)
    

See Also

Reference