Hooking Data up to ListBox and Datagrid

This is a walkthrough of how to hook data up to both ListBox and Datagrid. In this walkthrough, we'll create a small collection to use as the data source.

For this walkthrough, you'll need Visual Studio 2008, the new Microsoft Silverlight Tools Beta 1 for Visual Studio 2008, the Silverlight 2 SDK Beta 1, and the Silverlight 2 Beta 1 runtime. For Silverlight specific tools, go to Silverlight.net.

* This post walks through creating a C# project, but  there is also a VB version of the code at the bottom of the post
* Delay’s blog has some great info on how to use ListBox in various ways (he covers most of the key scenarios )
* When adding ListBox and DataGrid to Page.xaml, pay attention to the capitalization in each tag (e.g. <ListBox…and <..:DataGrid…)

 

Create a Silverlight 2 Project

Create a new Silverlight 2 project and a web application project to host it.

 

 

Layout a ListBox

In your Silverlight project, add a reference to System.Windows.Controls.Data. This will allow us to use the Datagrid control.

Open Page.xaml and remove the height and width settings from UserControl (shown as text with a strike through below). I do this so the Silverlight content can fill the web browser page rather than be restricted to a specified width and height.

Add vertical and horizontal alignment specifications to the LayoutRoot grid control, so the grid will align center on the page. Then, add a Margin of 50, so the grid has some buffer between it and the edges of the page. Next, add two rows to the grid that are each 50% of the total grid height, and then add a ListBox control to row 0, give it an x:Name attribute of “myListBox”, and a height and width (original xaml is shown in gray and new or modified xaml is shown in full color below).

<UserControl x:Class="DataSample.Page"

xmlns="http://schemas.microsoft.com/client/2007"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Width="400" Height="300">

<Grid

x:Name="LayoutRoot"

Background="White"

HorizontalAlignment="Center"

VerticalAlignment="Center"

Margin="50">

< Grid.RowDefinitions >

< RowDefinition Height ="50*" />

< RowDefinition Height ="50*" />

</ Grid.RowDefinitions >

< ListBox x : Name ="myListBox" Grid.Row ="0" Height ="200" Width ="300"/>

</Grid>

</UserControl>

Now, run your project and you should see an empty ListBox as shown below.

 

Create a Collection to Fill the ListBox

We need to fill the ListBox with data, and to do this we’re going to create a collection in code. We’re going to add two new classes to Page.xaml.cs, so open the file, and add a class called Peeps with a String property for FirstName, a String property for LastName, and an int property for Age. Also, add a class called PeepsList that inherits from List<>, and fill it with as many peeps as you like. You could, of course, create two new separate class files for this if you prefer.

Next, create an instance of the PeepsList collection in the Page class’s constructor and then set the ItemSource of the ListBox to this new instance (use the x:Name attribute for the ListBox you used in the xaml file).

Here’s my sample code; the code in full color is what I added to the file to accomplish what was described above.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace DataSample

{

public partial class Page : UserControl

{

//Constructor called on page load

public Page()

{

InitializeComponent();

//When the page loads create a new list of peeps

PeepsList listData = newPeepsList();

//Set the listbox "myListBox" ItemSource to the newly created list of peeps

myListBox.ItemsSource = listData;

}

}

//Defines peeps item content

publicclassPeeps

{

//Properties

publicString FirstName{ get; set; }

publicString LastName{ get; set; }

publicint Age{ get; set; }

//Constructor

public Peeps(String _fName, String _lName, int _Age)

{

FirstName = _fName;

LastName = _lName;

Age = _Age;

}

}

//Creates list of peeps to use in listbox and datagrid

publicclassPeepsList : List<Peeps>

{

//Constructor

public PeepsList()

{

this.Add(newPeeps("Lisa", "Martin", 19));

this.Add(newPeeps("Ilana", "James", 39));

this.Add(newPeeps("Halle", "Bora", 19));

this.Add(newPeeps("Jason", "DeVora", 29));

this.Add(newPeeps("Julie", "Jones", 10));

this.Add(newPeeps("George", "Hill", 30));

}

}

}

Now, run your project and your ListBox should look as follows.

 

Create an ItemTemplate to Control Presentation of Data

Our ListBox now shows the namespace and name of the Peeps class, so we need to create an ItemTemplate to control presentation of the data in the collection, and to do this you’ll need to open Page.xaml again.

We’re going to list the First Name property of each of the Peeps in our ListBox. To do this, add a ListBox.ItemTemplate tag, and inside of that add a DataTemplate tag, and inside of that add a Textblock and set the Text attribute’s Binding to FirstName, as shown below.

<UserControl x:Class="DataSample.Page"

xmlns="http://schemas.microsoft.com/client/2007"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Grid

x:Name="LayoutRoot"

Background="White"

HorizontalAlignment="Center"

VerticalAlignment="Center"

Margin="50">

<Grid.RowDefinitions>

<RowDefinition Height="50*" />

<RowDefinition Height="50*" />

</Grid.RowDefinitions>

<ListBox x:Name="myListBox" Grid.Row="0" Height="200" Width="300">

<ListBox.ItemTemplate>

<DataTemplate>

<TextBlock Text="{Binding FirstName}" Margin="5"/>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</Grid>

</UserControl>

Now, run your project and it should look as shown below.

 

Layout a DataGrid

Now, let’s add a Datagrid to our UI and fill it with the same data from the PeepsList. To do this, open Page.xaml and add a namespace reference to System.Windows.Controls.Data, and then add a DataGrid xaml element to the page and place it in row 1 of the grid. Be sure to add the AutoGenerateColumns =”True” attribute, so it automatically creates column headers, and give it an x:Name attribute of “myDataGrid”. The last thing to do to the DataGrid is to give it a height, width, and margin. All new xaml is shown below in full color below.

<UserControl x:Class="DataSample.Page"

    xmlns="http://schemas.microsoft.com/client/2007"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

 xmlns : data ="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" >

    <Grid

        x:Name="LayoutRoot"

        Background="White"

        HorizontalAlignment="Center"

        VerticalAlignment="Center"

        Margin="50">

        <Grid.RowDefinitions>

            <RowDefinition Height="50*" />

            <RowDefinition Height="50*" />

        </Grid.RowDefinitions>

        <ListBox x:Name="myListBox" Grid.Row="0" Height="200" Width="300">

            <ListBox.ItemTemplate>

  <DataTemplate>

                    <TextBlock Text="{Binding FirstName}" Margin="5"/>

                </DataTemplate>

            </ListBox.ItemTemplate>

        </ListBox>

< data : DataGrid x : Name ="myDataGrid” Grid.Row ="1" AutoGenerateColumns ="True" Height ="200" Width ="300" Margin ="10"/>

    </Grid>

</UserControl>

Now, open Page.xaml.cs and set myDataGrid’s ItemSource to the new PeepsList instance just as you did for the ListBox as shown below in full color.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace DataSample

{

public partial class Page : UserControl

{

//Constructor called on page load

public Page()

{

InitializeComponent();

//When the page loads create a new list of peeps

PeepsList listData = new PeepsList();

//Set the listbox "myListBox" ItemSource to the newly created list of peeps

myListBox.ItemsSource = listData;

//Set the datagrid "myDataGrid" ItemSource to the newly created list of peeps

myDataGrid.ItemsSource = listData;

}

}

//Defines peeps item content

public class Peeps

{

//Properties

public String FirstName{ get; set; }

public String LastName{ get; set; }

public int Age{ get; set; }

//Contructor

public Peeps(String _fName, String _lName, int _Age)

{

FirstName = _fName;

LastName = _lName;

Age = _Age;

}

}

//Creates list of peeps to use in listbox and datagrid

public class PeepsList : List<Peeps>

{

//Constructor

public PeepsList()

{

this.Add(new Peeps("Lisa", "Martin", 19));

this.Add(new Peeps("Ilana", "James", 39));

this.Add(new Peeps("Halle", "Bora", 19));

this.Add(new Peeps("Jason", "DeVora", 29));

this.Add(new Peeps("Julie", "Jones", 10));

this.Add(new Peeps("George", "Hill", 30));

}

}

}

Run your application and it should look as follows.

 

VB Version of Code

If you prefer to code in VB, here is the VB version of the code for Page.xaml.vb

Partial Public Class Page

Inherits UserControl

Public Sub New()

InitializeComponent()

'When the page loads create a new list of peeps

Dim listData As PeepsList = New PeepsList()

'Set the listbox "myListBox" ItemSource to the newly created list of peeps

myListBox.ItemsSource = listData

'Set the listbox "myListBox" ItemSource to the newly created list of peeps

myDataGrid.ItemsSource = listData

End Sub

End Class

'Defines peeps item content

Public Class Peeps

'Properties

Private fName As String

Public Property FirstName() As String

Set(ByVal Value As String)

fName = Value

End Set

Get

Return fName

End Get

End Property

Private lName As String

Public Property LastName() As String

Set(ByVal Value As String)

lName = Value

End Set

Get

Return lName

End Get

End Property

Private aAge As Integer

Public Property Age() As Integer

Set(ByVal Value As Integer)

aAge = Value

End Set

Get

Return aAge

End Get

End Property

'Contructor

Public Sub New(ByVal _fName As String, ByVal _lName As String, ByVal _age As Integer)

firstName = _fName

lastName = _lName

age = _age

End Sub

End Class

'Creates list of peeps to use in listbox and datagrid

Public Class PeepsList

Inherits List(Of Peeps)

'Contructor

Public Sub New()

Me.Add(New Peeps("Lisa", "Martin", 19))

Me.Add(New Peeps("Ilana", "James", 39))

Me.Add(New Peeps("Halle", "Bora", 19))

Me.Add(New Peeps("Jason", "DeVora", 29))

Me.Add(New Peeps("Julie", "Jones", 10))

Me.Add(New Peeps("George", "Hill", 30))

End Sub

End Class

Now, you can apply one of the custom styles I created in my previous post to further customize the UI you just created.