5,135,153 members and growing! (18,089 online)
Email Password   helpLost your password?
Desktop Development » Miscellaneous » General     Intermediate

The new WPF GridView customized 1 of 3

By Juan Pablo G.C.

Customize the WPF GridView and Binding multiple sources
C# 2.0, C# 3.0, C#, Windows, .NET, .NET 3.0, .NET 2.0VS2005, VS, Dev

Posted: 20 Jun 2007
Updated: 20 Jun 2007
Views: 32,983
Announcements



Search    
Advanced Search
Sitemap
21 votes for this Article.
Popularity: 5.76 Rating: 4.36 out of 5
2 votes, 9.5%
1
1 vote, 4.8%
2
0 votes, 0.0%
3
3 votes, 14.3%
4
15 votes, 71.4%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Screenshot - DC_12.png

Abstract

This article explains how to get data from many sources and add them to a gridview (WPF). Create the gridview and after customize it in a WPF application.

Index

  • Introduction
  • Prerequisites
  • Creating the Gridview
  • XML Databinding
    • Renember XML and .net 2.0
    • XML Binding using only XAML
    • XML Binding using XAML and C#
  • SQL Server Binding
  • Access Binding
  • MySql Binding
  • Customizing the Gridview
    • Customize the header
    • Customize the background
    • Customize the rows

Introduction

The gridview is one of the possiblities to show a listview, you can customize it in many ways, at the moment there's few information and its customization is not very well implemented in Blend yet (you can't design it without viewing XAML code). Another matter is that in Blend you can bind XML data but what happen with the rest of datasources, how I dont see anyway in XAML I show how to Bind to XAML from C#.

Prerequisites

To get successful with the article you wil need the next software:

  • Visual Studio 2005 C# (Or Express C# Orcas).
  • WPF Extensions for VS2005 (included in Orcas).
  • Framework 3.0
  • MS Expression Blend.
  • SQL Server 2005 Express (optional).
  • MS Access 2003 or higher (optional).
  • MySql Server (optional).

Creating the gridview

First of all create a new project, type project C# NET Framework 3.0: Window Application (WPF).

Now add a ListView (not a ListBox), from "All Controls" section in toolbox, and change the Name to "DataList", you will have a code like:

<Window x:Class="sample1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml"
    Title="sample1" Height="320" Width="500"
    >
    <Grid>
    <ListView Margin="0,0,0,50" Name="DataList" />
  </Grid>
</Window>

Take a look to the Window.g.cs code, if is added the internal DataList will be ok, if not add the next line:

internal System.Windows.Controls.ListView DataList;

You don't need to initializate it because it exists in the XAML section. Run the project to be sure all is working.

XML Databinding

Here I explain in a code explanation how to bind from xml using only xaml (static version) and then from xml with XAML and C# (my favourite way) because is easier to change on runtime the source.

I will use in this section the next called "data.xml" file:

 <Customers>
  <Customer>
 <Code>1234</Code>
 <Name>EPI</Name>
 <Country>Sesame Street</Country>
  </Customer>
  <Customer>
 <Code>3234</Code>
 <Name>Paul</Name>
 <Country>United Kingdom</Country>
  </Customer>
 <Customer>
 <Code>3344</Code>
 <Name>Juan</Name>
 <Country>Spain</Country>
  </Customer>
 <Customer>
 <Code>4321</Code>
 <Name>Dodo</Name>
 <Country>Mars</Country>
  </Customer>
</Customers>

Renember XML and .net 2.0

To bind XML data to a DataGridView in .net 2.0, you have to add the next code:

string file = "data.xml";
DataSet ds = new DataSet("Table");
ds.ReadXml(file);
dG1.DataSource = ds.Tables[0].DefaultView;

and you will have a fast way to show data:

Screenshot - DC_1.png

XML binding using only XAML

In this case, first you have to create a new Window.Resource:

<Window.Resources>
    <XmlDataProvider x:Key="CustomersDS" Source="C:\data.xml"/>
</Window.Resources>

and now we have to change the listview to have a gridview aspect:

<ListView Margin="0,0,0,50" ItemTemplate="{DynamicResource CustomerTemplate}" ItemsSource="{Binding Source={StaticResource CustomersDS}, XPath=/Customers/Customer}">
      <ListView.View>
        <GridView>
          <GridViewColumn Header="Code" DisplayMemberBinding="{Binding XPath=Code}"/>
          <GridViewColumn Header="Name" DisplayMemberBinding="{Binding XPath=Name}"/>
          <GridViewColumn Header="Country" DisplayMemberBinding="{Binding XPath=Country}"/>
        </GridView>
      </ListView.View>
</ListView>

With this method you will have a static XML binding using only XAML:

Screenshot - DC_2.png

XML binding using XAML and C#

Generate the "data.xml" shown before, and (that's the way I like code), create the method OnLoad. To do that add the "Loaded" event to the XAML <window> tag:

<Window x:Class="WindowsApplication7.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation"

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

    ...
    Loaded="OnLoad"
>

And in the window1.xaml.cs add the namespace using System.Data; and the method:

public void OnLoad(Object o, EventArgs e)
{
            string file = @"c:\data.xml";
            DataSet ds = new DataSet("Table");
            ds.ReadXml(file);
            List1.DataContext = ds.Tables[0].DefaultView;
}

Now you have to assign the link between "Table" and "BindingPath" in the XAML with the next code:

<Grid x:Name="LayoutRoot">
    <ListView Name="List1" Margin="35,34,212,123" ItemTemplate="{DynamicResource CustomerTemplate}" ItemsSource="{Binding Path=Table}">
      <ListView.View>
        <GridView>
          <GridViewColumn Header="Code" DisplayMemberBinding="{Binding Path=Code}"/>
          <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
          <GridViewColumn Header="Country" DisplayMemberBinding="{Binding Path=Country}"/>
        </GridView>
      </ListView.View>
    </ListView>
</Grid>

To understand better the link between XAML and C# take a look to this diagram:

Screenshot - DC_3.png

Loaded Calls OnLoad that fills the table and paints on gridview. I like this way because you can change easily the datasource.

SQL Server Binding

Create a new database call "Customers" and create inside the table "customers" with this structure:

Screenshot - DC_4.png

Y añadimos datos de ejemplo en la tabla:

Screenshot - DC_5.png

Renember that the user must have a role to access to this database and activate datareader and datawriter:

Screenshot - DC_6.png

Now add the namespace: using System.Data.SqlClient; and the modify the previous OnLoad method to have:

public void OnLoad(Object o, EventArgs e)
{
    string s_command = "SELECT Code,Name,Country FROM customers";
    SqlConnection connection = new SqlConnection();
    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand command = new SqlCommand();
    command.CommandText = s_command;
    adapter.SelectCommand = command;
    connection.ConnectionString = "Data Source=192.168.10.9,1433;Initial Catalog=Customers;Network Library=DBMSSOCN;User ID=temporalguest;Password='';";
    command.Connection = connection;
    DataSet ds = new DataSet();
    adapter.Fill(ds,"Table");
    List1.DataContext = ds.Tables[0].DefaultView;
    connection.Close();
} 

NOTE: The SQL queries are not casesensitives, the XAML are CASESENSITIVES so, the name of the columns have to be the same of the name of DisplayMemberBinding.

Access DataBinding

Open Access and create a new database called "customers.mdb" and add inside the table "customers" like the previous section.

Add the namespace using System.Data.OleDb; and simply modify the OnLoad method to the next:

public void OnLoad(Object o, EventArgs e)
{
   string s_command = "SELECT Code,Name,Country FROM customers";
   OleDbConnection connection = new OleDbConnection();
   OleDbDataAdapter adapter = new OleDbDataAdapter();
   OleDbCommand command = new OleDbCommand();
   command.CommandText = s_command;
   adapter.SelectCommand = command;
   connection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\customers.mdb";
   connection.Open();
   command.Connection = connection;
   DataSet ds = new DataSet();
   adapter.Fill(ds);
   List1.DataContext = ds.Tables[0].DefaultView;
   connection.Close();
}

MySql Databinding

Requisites to have a successful compilation:

- Download and install the namespace MySql.Data from: http://dev.mysql.com/get/Downloads/Connector-Net/mysql-connector-net-5.0.7.zip/from/pick#mirrors

- In the project, add the reference to MySql.Data from the solution explorer:

Screenshot - DC_7.png

Being care we have correctly installed MySQLServer, simply add the namespace using MySql.Data.MySqlClient and change the OnLoad method to:

public void OnLoad(Object o, EventArgs e)
{
  string s_command = "SELECT Code,Name,Country FROM customers";
  MySqlConnection connection = new MySqlConnection();
  MySqlCommand command = new MySqlCommand();
  MySqlDataAdapter adapter = new MySqlDataAdapter();
  command.CommandText = s_command;
  adapter.SelectCommand = command;
  connection.ConnectionString = "Server=192.168.10.9;Database=Customers;User Id=temporalguest;Password=111111;";
  command.Connection = connection;
  DataSet ds = new DataSet();
  adapter.Fill(ds, "Table");
  List1.DataContext = ds.Tables[0].DefaultView;
  connection.Close();
}

Customizing the GridView

In this article I show how to customize the main aspects of the gridview, this is a strange control in WPF because is not accessible from Blend in design time, so here I explain how to customize it in XAML code.

Customize the header

If you want to customize the header of every column add the next code in the Listview tag:

<GridView ColumnHeaderTemplate="{StaticResource BlueHeader}">

In the case you want to customize per column add the next code:

<GridViewColumn Header="Code" DisplayMemberBinding="{Binding Path=Code}" HeaderTemplate="{StaticResource BlueHeader}" />

Now simply add the resource in the <Window> tag:

<Window.Resources>
    <DataTemplate x:Key="BlueHeader">
      <StackPanel Orientation="Horizontal" Margin="-5,-5,-5,-5" Width="120">
        <StackPanel.Background>
          <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="#FF223B84" Offset="1"/>
            <GradientStop Color="#FF57A0F4" Offset="0.5"/>
            <GradientStop Color="#FF4B94EC" Offset="0.5"/>
          </LinearGradientBrush>
        </StackPanel.Background>
        <TextBlock Margin="10,10,10,10" Text="{Binding}" VerticalAlignment="Center"  Foreground="White"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

Now we will have a gridview like:

Screenshot - DC_9.png

Customize the Background

That's too easy, you can do it in Blend if you want, the code you need to add in the <ListView> tag is:

<ListView.Background>
        <LinearGradientBrush EndPoint="0.939,0.919" StartPoint="0.061,0.081">
          <GradientStop Color="#FFFFE07E" Offset="0"/>
          <GradientStop Color="#FFFFFAEA" Offset="1"/>
        </LinearGradientBrush>
</ListView.Background>

And then we will have:

Screenshot - DC_10.png

Customize the rows

First let's change the typical style of the rows, to do that simply add the next XAML code in the <ListView> tag:

<ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}"  >
          <Setter Property="Height" Value="24" />
          <Setter Property="Background" Value="#5EF4E057" />
          <Setter Property="Foreground" Value="#FF4B94EC"/>
        </Style>
</ListView.ItemContainerStyle>

Now add XAML code to change when the mouse is over, to do that add a XAML style trigger, with the typical and mouse over code you will have:

<ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}"  >
          <Setter Property="Height" Value="24" />
          <Setter Property="Background" Value="#5EF4E057" />
          <Setter Property="Foreground" Value="#FF4B94EC"/>
          
          <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
              <Setter Property="Foreground" Value="DarkBlue" />
              <Setter Property="Background">
                <Setter.Value>
                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FFFFC704" Offset="0.986"/>
                    <GradientStop Color="#FFF4E057" Offset="0.5"/>
                    <GradientStop Color="#FFF4E057" Offset="0.51"/>
                  </LinearGradientBrush>
                </Setter.Value>
              </Setter>
            </Trigger>
            
          </Style.Triggers>
        </Style>
</ListView.ItemContainerStyle>

and finally you will have a well styled gridview that was really hardcoding in previous versions of .net:

Screenshot - DC_12.png

In Next Chapter...

I will explain:

  • Adding data from an ArrayList.
  • Grouping data in the gridview.
  • More style customization.
  • Editing data of the gridview.
  • Adding controls to the gridview.

Release History

1.0 Original version of the article

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Juan Pablo G.C.


Mvp
I'm an Electronic Engineer, I did my end degree project at Astrophysical Institute and Tech Institute. I'm HP Procurve AIS and ASE helping at University, and I'm getting ready for Microsoft MCTS.
I live in Canary Islands. At the moment Im developing a CRM software for my company. I'm really interested know people getting the MCTS.
I'm an SQL Server and .net2.0 intermediate expert.

Take a look to my blog Juan Pablo G.C.
Overrider
Occupation: Web Developer
Location: Spain Spain

Other popular Miscellaneous articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralSet other Background than default Blue when a ListViewItem is selectedmemberpixel3cs6:36 10 May '08  
GeneralTotal Row?memberDan Hunt10:33 25 Oct '07  
GeneralPlease post the next threadmemberHunny Tomar21:21 18 Oct '07  
Generalalignment and columns widthmemberwebspeed7:22 15 Oct '07  
GeneralHere is my new one JuanmemberSacha Barber11:03 25 Jul '07  
GeneralXAML How to get parent propertymemberJuan Pablo G.C.0:19 16 Jul '07  
GeneralRe: XAML How to get parent propertymemberSacha Barber21:40 23 Jul '07  
GeneralWhat happens whenmemberSacha Barber8:00 12 Jul '07  
GeneralRe: What happens whenmemberJuan Pablo G.C.0:18 13 Jul '07  
GeneralRe: What happens whenmemberSacha Barber0:26 13 Jul '07  
GeneralI have just solved (without the trigger matters)memberJuan Pablo G.C.2:37 13 Jul '07  
GeneralRe: I have just solved (WITH the trigger matters)memberJuan Pablo G.C.3:59 13 Jul '07  
GeneralRe: I have just solved (WITH the trigger matters) and header text colormemberJuan Pablo G.C.4:43 13 Jul '07  
GeneralRe: I have just solved (WITH the trigger matters) and header text colormemberSacha Barber6:18 13 Jul '07  
GeneralRe: I have just solved (WITH the trigger matters) and header text colormember