May 15, 2009 12:05 AM

Columns & Rows: Part I

Silverlight 2.0 DataGrid Properties
DevConnections
Rating: (0)

asp:Feature

LANGUAGES: C#

ASP.NET VERSIONS: 3.5

Columns & Rows:
Part I

Silverlight 2.0 DataGrid Properties

By Bilal Haidar

There is a need in every database-drivenapplication to display data to end-users in the form of rows and columns thatmimic the Excel sheets with which most end-users are familiar. Fortunately forus, Silverlight provides a rich and robust DataGrid control.

The Silverlight team at Microsoft issued the firstrelease of the DataGrid in October 2008. This release had so many issues theteam was forced to release an updated version in December 2008. This is themost up-to-date release, and includes more than 30 bug fixes. To read moreabout that latest release, visit the Silverlight 2 DataGrid December 2008Release blog post by Scott Morrison, the project manager of the SilverlightDataGrid (blogs.msdn.com/scmorris/archive/2008/12/19/silverlight-2-datagrid-december-2008-release.aspx).

Working with the Silverlight 2.0 DataGrid is notdifficult; however, having a series of articles dissecting its details can bebeneficial, so this is exactly what I intend to do in this series.

Introduction

This article is the first in a series that willtackle most of the features of the Silverlight 2.0 DataGrid. There are severalsections to discuss and explain regarding the Silverlight 2.0 DataGrid,including an overview of the DataGrid properties, auto-generating columns,defining columns in XAML, defining columns at runtime, implementingmaster/detail features, paging and sorting, and editing/deleting/adding rowsusing the DataGrid.

Through the course of this article, you ll get anoverview of the majority of the DataGrid properties that play an important rolein configuring the DataGrid, like setting the column width and row color, andalternating colors, among other things.

References to Silverlight 2.0

This article assumes you have a fair knowledge ofusing Silverlight 2.0 especially data-binding features and is not intended asan introduction to Silverlight 2.0. If you feel you need more information onSilverlight 2.0, I recommend you check the official website at www.silverlight.net, where you ll finddozens of articles and videos to get you started. Another major resource forlearning Silverlight 2.0 is www.silverlightshow.net;it focuses on delivering rich and comprehensive tutorials on Silverlight.

Additionally, you can download the Microsoft Silverlight2.0 SDK documentation, which covers all the features of Silverlight (www.microsoft.com/Downloads/details.aspx?familyid=BCE7684A-507B-4FC6-BC99-6933CD690CAB&displaylang=en).

The Silverlight DataGrid

To start, let s create a new Visual Studio 2008Silverlight application. The Silverlight Application template has been integratedinto Visual Studio 2008. When creating the new application, make sure to selectthe Add a new ASP.NET Web project to the solution to host Silverlight option,as shown in Figure 1.

Figure 1

Figure 1: Silverlight configuration screen

Selecting this option will create for you anASP.NET Web project that hosts the Silverlight application; this also providesmore flexibility for you as a developer to make use of all the ASP.NET featuresto which you are already accustomed.

Before we start with the details of adding theDataGrid and exploring its properties, the final product will be somethingsimilar to what is shown in Figure 2.

Figure 2

Figure 2: DataGrid properties view

As you can see in this demonstration, the DataGridis on top, with the major properties to be discussed shown as separaterectangles, each with a title representing the property title and the bodyrepresenting the different values that the property can accept.

Adding a DataGrid to a User Control

To add a DataGrid to a Silverlight User Control,all you need to do is drag the DataGrid control from the Silverlight XAMLControls toolbox that is only available for Silverlight applications. You canonly drag controls on to the XAML part of the User Control because the DesignView is still read-only for Silverlight applications. The dragged DataGridcontrol is shown in Figure 3.

<!-- DataGrid -->

<data:DataGrid x:Name="dgEmployees"Width="500" />

Figure 3: Silverlight DataGrid control

Adding the DataGrid as shown in Figure 3 adds tothe User Control header the XAML namespace shown in Figure 4.

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

assembly=System.Windows.Controls.Data"

Figure 4: DataGrid XAML namespace

This is to say that the DataGrid control is locatedin the System.Windows.Controls namespace that is part of theSystem.Windows.Controls.Data assembly. This is required, because the DataGridis only available as part of the Silverlight 2.0 Software Development Kit(SDK).

 

Adding a DataGrid this way without configuring anyproperties yields default values for some of the major properties (see Figure5).

Property Name Default Value
AutoGenerateColumns TRUE
CanUserReorderColumns TRUE
CanUserResizeColumns TRUE
CanUserSortColumns TRUE
MaxColumnWidth double.PositiveInfinity
MinColumnWidth 20
RowDetailsVisiblityMode DataGridRowDetailsVisibilityMode.VisibleWhenSelected
RowHeight 2
SelectionMode DataGridSelectionMode.Extended
HorizontalGridLinesThinkness 1
ColumnHeaderHeight 4
RowHeaderWidth 4

Figure 5: Major DataGrid properties

Now that you know how to add a DataGrid, let sstart building each property s UI and explain how to use it, as well as itseffect on the DataGrid.

DataGrid Properties

In this section, the major DataGrid properties willbe listed together with a detailed explanation of the UI used to present theproperty and the code-behind that puts the properties selected values intoeffect by applying them to the DataGrid.

The GridLinesVisibility Property

This property controls the display of thehorizontal or vertical grid lines separating the inner cells of the DataGrid.It is of type DataGridLinesVisibility enumeration.

The XAML UI in Figure 6 shows a StackPanel controlholding a TextBlock control as a title, together with a ListBox control listingall the available values the GridLinesVisibility property accepts.

<StackPanel >

<Border >

<TextBlock Text="GridLinesVisibility"/>

</Border>

<ListBoxx:Name="lstboxGridLinesVisibility"

SelectionChanged="lstboxGridLinesVisibility_SelectionChanged">

<TextBlockText="All" />

<TextBlockText="Horizontal" />

<TextBlockText="None" />

<TextBlockText="Vertical" />

</ListBox>

</StackPanel>

Figure 6: XAML UI of the GridLinesVisibilityproperty

AcceptableValue(s). The GridLinesVisibility property is a Dependency property and cantake any of the following values:

  • Horizontal: Only horizontal grid lines aredisplayed.
  • Vertical: Only vertical grid lines aredisplayed.
  • None: The DataGrid is displayed without any gridlines.

Each of the above values is displayed as aTextBlock control inside the ListBox control.

Code-behind.The ListBox control listing the acceptable values of theGridLinesVisibility property defines an event handler for the SelectionChangedevent (see Figure 7).

The event handler in Figure 7 starts by getting areference to the TextBlock control representing the value selected in theListBox control. After that, the GridLinesVisibility property is set on theDataGrid by casting the value in to a DataGridGridLinesVisibility enumeration.Based on the item selected, the DataGrid will behave accordingly.

private void lstboxGridLinesVisibility_SelectionChanged(

object sender,SelectionChangedEventArgs e)

{

TextBlock option =

e.AddedItems[0] asTextBlock;

if(option.Text.Equals(""))

return;

this.dgEmployees.GridLinesVisibility = (DataGridGridLinesVisibility)

Enum.Parse(typeof(DataGridGridLinesVisibility), option.Text, true);

}

Figure 7: Define an event handler for theSelectionChanged event of the GridLinesVisibility property

The HeadersVisibility Property

This property controls the display of column androw headers on the DataGrid control. You are likely familiar with the columnheaders; however, the row header is a new feature added to a DataGrid thatshows an empty cell beside each row, and hence acts as a header for every rowdisplayed in the DataGrid. This property is of type HeadersVisibilityenumeration.

The XAML UI in Figure 8 shows a StackPanel controlholding a TextBlock control as a title, together with a ListBox control listingall the available values the HeadersVisibility property accepts.

<StackPanel >

<Border >

<TextBlockText="HeadersVisiblity" />

</Border>

<ListBoxx:Name="lstboxHeadersVisiblity"

SelectionChanged="lstboxHeadersVisiblity_SelectionChanged">

<TextBlock Text="All"/>

<TextBlockText="Column" />

<TextBlockText="None" />

<TextBlockText="Row" />

</ListBox>

</StackPanel>

Figure 8: XAML UI of the HeadersVisibilityproperty

AcceptableValue(s). The HeadersVisibility property is a Dependency property and cantake any of the following values:

        Column: Only column headers are displayed.

        Row: Only row headers are displayed.

        All: Both column and row headers are displayed.

        None: Both column and row headers are notdisplayed.

Each of the above values is displayed as aTextBlock control inside the ListBox control.

Code-behind.The ListBox control listing the acceptable values of the HeadersVisibilityproperty defines an event handler for the SelectionChanged event (see Figure9).

private void lstboxHeadersVisibility_SelectionChanged(

object sender,SelectionChangedEventArgs e)

{

TextBlock option =

e.AddedItems[0] asTextBlock;

if(option.Text.Equals(""))

return;

this.dgEmployees.HeadersVisibility = (DataGridHeadersVisibility)

Enum.Parse(typeof(DataGridHeadersVisibility), option.Text, true);

}

Figure 9: Define an event handler for theSelectionChanged event of the HeadersVisibility property

The event handler in Figure 9 starts by getting areference to the TextBlock control representing the value selected in theListBox control. After that, the HeadersVisibility property is set on theDataGrid by casting the value in to a DataGridHeadersVisibility enumeration.Based on the item selected, the DataGrid will behave accordingly.

The RowBackground Property

This property decides on the Brush that is used topaint the background color of rows in a DataGrid. It is of type Brush.

The XAML UI in Figure 10 shows a StackPanel controlholding a TextBlock control as a title, together with a ListBox control listingsome color names that will be used to change the row background colors for theDataGrid rows.

<StackPanel>

<Border >

<TextBlockText="RowBackground" />

</Border>

<ListBox x:Name="lstboxRowBackground"

SelectionChanged="lstboxRowBackground_SelectionChanged">

<TextBlockText="Red" />

<TextBlockText="Beige" />

<TextBlockText="Blue" />

<TextBlockText="Remove Color" />

</ListBox>

</StackPanel>

Figure 10: XAML UI of the RowBackgroundproperty

AcceptableValue(s). The RowBackground property is a Dependency property and can takeonly values of type Brush.

Code-behind.The ListBox control listing some color names defines an event handler for theSelectionChanged event (see Figure 11).

private void lstboxRowBackground_SelectionChanged(

object sender,SelectionChangedEventArgs e)

{

TextBlock option =e.AddedItems[0] as TextBlock;

if(option.Text.Equals(""))

return;

this.dgEmployees.RowBackground=

(Brush)this.Resources[option.Text];

}

Figure 11: Define an event handler for theSelectionChanged event of the RowBackground property

The event handler in Figure 11 starts by getting areference to the TextBlock control representing the color value selected in theListBox control. Then the RowBackground property is set on the DataGrid bycasting in to a Brush object a resource object that was already defined in theXAML. Based on the color selected, the DataGrid s row backgrounds will changeaccordingly.

The trick here is to define a set of color brushesin the XAML part of the User Control and place them as part of the UserControl s resources:

<!-- Colors -->

<SolidColorBrush x:Key="Red" Color="Red"

Opacity=".8" />

<SolidColorBrush x:Key="Beige"Color="Beige"

Opacity=".8"/>

A separate SolidColorBrush is defined for everycolor intended to be added. Once the colors are added as User Controlresources, they can be accessed in the code-behind by accessing the ResourceDictionaryusing an indexer; in this case, the key name that was used to define the colorBrush in XAML. Once a resource item is retrieved, it is cast to its proper type(in this case, Brush type).

The FrozenColumnCount Property

This property controls the number of columns theuser will not be able to scroll horizontally. In other words, the value of thisproperty determines the columns that will be frozen, and on which thehorizontal scrollbar will not act.

The XAML UI in Figure 12 shows a StackPanel controlholding a TextBlock control as a title, together with a ListBox control listingsome integer values that will be used to control the FrozenColumnCount propertyof the DataGrid.

<StackPanel >

<Border >

<TextBlockText="FrozenColumnCount" />

</Border>

<ListBoxx:Name="lstboxFrozenColumnCount"

SelectionChanged="lstboxFrozenColumnCount_SelectionChanged">

<TextBlockText="1" />

<TextBlockText="2" />

<TextBlockText="None" />

</ListBox>

</StackPanel>

Figure 12: XAML UI of the FrozenColumnCountproperty

AcceptableValue(s).The FrozenColumnCount property is a Dependency property and cantake only integer values. Specifying an integer value represents the number ofcolumns to freeze while scrolling with the horizontal scrollbars. To freeze thefirst column, set the value to 1 . To freeze the second column, set the valueto 2 , thus freezing the first two columns at once.

Code-behind.The ListBox control listing some color names defines an event handler forthe SelectionChanged event (see Figure 13).

private void lstboxFrozenColumnCount_SelectionChanged(

object sender,SelectionChangedEventArgs e)

{

TextBlock option =e.AddedItems[0] as TextBlock;

if(option.Text.Equals(""))

return;

this.dgEmployees.FrozenColumnCount =

option.Text.Equals("None") ? 0 : Int32.Parse(option.Text);

}

Figure 13: Define an event handler for theSelectionChanged event of the FrozenColumnCount property

The event handler in Figure 13 starts by getting areference to the TextBlock control representing the integer value selected inthe ListBox control. If the selected value was None , which is a special valueadded to represent 0 columns frozen, the DataGrid is configured with a valueof 0 on the FrozenColumnCount, else the exact number selected in the ListBoxcontrol is cast to an integer and assigned on the FrozenColumnCount property.

The SelectionMode Property

This property controls the selection of a single ormultiple rows in a DataGrid. In general, the DataGrid has two main selectionmodes; either a single selection, which means only one row, can be selected atonce, or extended selection mode, which allows the selection of multiple rows.This property is of type DataGridSelectionMode enumeration.

The XAML UI in Figure 14 shows a StackPanel controlholding a TextBlock control as a title, together with two RadioButton controlsfor each of the possible values that the SelectionMode property accepts.

<StackPanel>

<Border>

<TextBlockText="SelectionMode" />

</Border>

<Border>

<GridHeight="Auto" Width="Auto">

<Grid.RowDefinitions>

<RowDefinition Height="Auto" />

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="75" />

<ColumnDefinition Width="75" />

</Grid.ColumnDefinitions>

<RadioButtonx:Name="rbtnSingle"

Content="Single" Checked="rbtnSingle_Checked"

GroupName="grSelectionMode"/>

<RadioButtonx:Name="rbtnExtended"

Content="Extended" Checked="rbtnSingle_Checked"

GroupName="grSelectionMode" />

</Grid>

</Border>

</StackPanel>

Figure 14: XAML UI of the SelectionModeProperty

AcceptableValue(s). The SelectionMode property is a Dependency property and can takeeither of the following values:

        Single: A single row can be selected at a time.

        Extended: Multiple rows can be selected at once.

Each of the above values is displayed as aRadioButton control.

Code-behind. Theabove two RadioButton controls define the same event handler for the Checkedevent. Checking either of these two controls triggers the Checked event. Toforce only one of the RadioButtons to be checked at a time, you must add theGroupName to both RadioButtons and make sure they have the same group name, andthus only one RadioButton in a single group can be checked at a time. TheRadioButtons Checked event handler is defined in Figure 15.

private void rbtnSingle_Checked(object sender, RoutedEventArgs e)

{

if(this.rbtnSingle.IsChecked.Value)

this.dgEmployees.SelectionMode = DataGridSelectionMode.Single;

if(this.rbtnExtended.IsChecked.Value)

this.dgEmployees.SelectionMode = DataGridSelectionMode.Extended;

}

Figure 15: The RadioButtons Checked eventhandler

Based on what the user has selected, thecorresponding SelectionMode value is set on the DataGrid.

The CanUserReorderColumns Property

This property is of type Boolean; it allows orprevents the user from selecting a column, then dragging and changing its orderamong the other columns displayed in the DataGrid. When the property is set to true , the user is allowed to drag a column and change its position on the DataGrid,thus reordering the columns displayed.

The XAML UI in Figure 16 shows a StackPanel controlholding a TextBlock control as a title, together with two RadioButton controls,one for the true value and one for the false value that the CanUserReorderColumnsproperty accepts.

<StackPanel>

<Border>

<TextBlockText="CanUserReorderColumns" />

</Border>

<Border >

<GridHeight="Auto" Width="Auto">

<Grid.RowDefinitions>

<RowDefinition Height="Auto" />

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="60" />

<ColumnDefinition Width="60" />

</Grid.ColumnDefinitions>

<RadioButtonx:Name="rbtnCanUserReorderColumns"

Content="True"Checked="rbtnCanUserReorderColumns_Checked"

GroupName="grCanUserReorderColumns" />

<RadioButtonx:Name="rbtnCannotUserReorderColumns"

Content="False"Checked="rbtnCanUserReorderColumns_Checked"

GroupName="grCanUserReorderColumns" />

</Grid>

</Border>

</StackPanel>

Figure 16: XAML UI of theCanUserReorderColumns property

AcceptableValue(s). The CanUserReorderColumns property is a Dependency property andcan take either a true or false value:

        True: User is allowed to rearrange the DataGridcolumns.

        False: Column rearrangement is not allowed inthe DataGrid.

Each of the above values is displayed as aRadioButton control.

Code-behind.The above two RadioButton controls define the same event handler for theChecked event. Checking either of these two controls triggers the Checkedevent. To force only one of the RadioButtons to be checked at a time, you mustadd the GroupName to both RadioButtons and make sure they have the same groupname so only one RadioButton in a single group can be checked at a time. TheRadioButtons Checked event handler is defined in Figure 17.

private void rbtnCanUserReorderColumns_Checked(

object sender,RoutedEventArgs e)

{

if(this.rbtnCanUserReorderColumns.IsChecked.Value)

this.dgEmployees.CanUserReorderColumns = true;

if(this.rbtnCannotUserReorderColumns.IsChecked.Value)

this.dgEmployees.CanUserReorderColumns = false;

}

Figure 17: The RadioButtons Checked eventhandler

Based on what the user has selected, thecorresponding CanUserReorderColumns value is set on the DataGrid, thus allowingor preventing a user from reordering the DataGrid columns.

There are additional major properties that can bemanipulated on the DataGrid control. The code download accompanying thisarticle explores additional important properties; take some time to explore howthey are implemented. I also suggest you visit bhaidar.net/SilverlightDataGrid/GridProperties.aspxto browse a live sample and play around with all the major DataGrid properties.

Conclusion

This article is the first in a series covering theSilverlight 2.0 DataGrid control. This installment provides an overview of theDataGrid properties and how they can be used to configure the behavior of theDataGrid.

Source code accompanying this article is available for download.

Bilal Haidar (bhaidar@gmail.com) is a Microsoft MVP inASP.NET. He is an MCP, MCTS, MCPD, MCT, and Telerik MVP. He is a lead softwaredeveloper at CCC, a multinational construction company based in Athens, Greece.

Add a Comment

There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement




Comments from the DevConnections Community

Join our community of development pros.

Windows problem

I all, I have a problem on my Windows Vista that began afetr the purchase of an external Hard Disk Freecom. A few days afetr the purchase I discon...

Most Recent Posts

GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS