How to use DataGrid in WPF with .NET 4.0

No.of Views22491
Bookmarked2 times
Downloads 
Votes2
By  RRaveen   On  01 Jul 2010 10:07:17
Tag : WPF , Data Binding
This is article explains how to use the DataGrid control in Windows Presentation Foundation in different ways
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

This is article explains how to use the DataGrid control in Windows Presentation Foundation in different ways. In this earlier version of the .NET Framework (.NET 3.0 and .NET 3.5) does not have DataGrid Control support to the WPF.But in .NET 4.0 Microsoft has support too directly to bind data in WPF to DataGrid as toolbox control.

Step 1

Create WPF application using visual studio 2010.

Image Loading

Step 2

Once you are created WPF project, then you will see like following, 

Image Loading

Step 3

Then remove the Grid xaml tags from the window, and drag and drop the DataGrid control from the toolbox and place inside the design surface. 

Image Loading

Once you place DataGrid inside the surface, the XAML will look like following,

<Window x:Class="WPFDemo01.Window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="Window1" Height="300" Width="300"><DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid1" Width="200" /></Window>

See in above XAML code there a key attributes marked like windows form GridView.

AutoGenerateColumns="False"

When you are set AutogenerateColumns is false to DataGrid, then we have to build the column structure.

Step 4.

I have decided to create three different samples to bind data to DataGrid

1.    Auto Generating Columns
2.    Defines Columns
3.    Format Column data using StringFormat

Note: End of this article has all samples project download.

Step 5 : Auto Generate Columns

First I have change the XAML code to support to auto generate columns properties true, when we are bind data to DataGrid.

MainWindow.xaml

<Window x:Class="WPFDemo01.Window1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="Window1" Height="300" Width="300"><DataGrid AutoGenerateColumns="True" Height="200" Name="dataGrid1" Width="200"></DataGrid></Window>

Then I have created static DataManager class to get the data from the database and bind to DataGrid.

DataManager.cs

using System.Data;
using System.Data.SqlClient;
using System.Windows.Controls;

namespace WPFDemo01
{public class DataManager
    {public static void BindData(DataGrid grid)
        {using (SqlConnection connection = new SqlConnection("ConnectionString"))
            {string sql = "select * from user_details;";using (SqlDataAdapter adapter = new SqlDataAdapter(sql, connection))
                {
                    DataSet data = new DataSet();
                    adapter.Fill(data);
                    grid.ItemsSource = data.Tables[0].DefaultView;
                }
            }
        }
    }
}

 MainWindow.xaml.cs

using System.Windows;
using System.Data.SqlClient;
using System.Data;

namespace WPFDemo01
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window
    {public MainWindow()
        {
            InitializeComponent();
        }private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataManager.BindData (this.dataGrid1);
        }
       
    }
}

In above code within the load event, call the BindData method. BindData method is implemented inside the DataManager Class.Inside the DataManager class, just read data from the database base and set to ItemSource to DataGrid control.

Note: We are unable to Bind DataTable to DataGrid ItemSouce property, because ItemSource is IEnumerable. So I has created the DataView from the table and then set as ItemSource.

Output

Image Loading

Step 6: Define Columns

In this section, just I’m going to stop Auto generating columns false, and then I manually define columns what are columns only need to show in DataGrid.

CustomColumnDataGridWin.xaml

<Window x:Class="WPFDemo01.CustomColumnDataGridWin"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="Custom Column in DataGrid" Height="400" Width="400" Loaded="Window_Loaded"><Grid><DataGrid AutoGenerateColumns="False" Name="datagrid1" Margin="0,0,0,0" Width="380" Height="380"><DataGrid.Columns><DataGridTextColumn Header="Member ID" Width="100" Binding="{Binding Path=MemberID}"></DataGridTextColumn><DataGridTextColumn Header="First Name" Width="120" Binding="{Binding Path=FName}"></DataGridTextColumn><DataGridTextColumn Header="Alias Name" Width="120" Binding="{Binding Path=AliasName}"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid></Window>

 In above XAML, I need only three columns such as MemberID, First Name and Alias Name. I have not change the fetch code inside the DataManager. Just only change code inside the CustomColumnDataGridWin.xaml.cs and XAML.

CustomColumnDataGridWin.xaml.cs

using System.Windows;
using System.Windows.Controls;

namespace WPFDemo01
{/// <summary>/// Interaction logic for CustomColumnDataGridWin.xaml/// </summary>public partial class CustomColumnDataGridWin : Window
    {public CustomColumnDataGridWin()
        {
            InitializeComponent();
        }private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataManager.BindData(this.datagrid1);this.datagrid1.ColumnWidth = DataGridLength.Auto;
        }
    }
}

Here I have set another additional property to DataGrid. The ColumnsWidth is set by content of the columns. Its means when we are set auto, every column width will decide the maximum length data on that particular column.

Output 

Image Loading

Step 7:Format coumns

Use the StringFormat class to format the column values based on type of data. In order to do this we have to modify the XAML like following to DataGrid.

CustomColumnDataGridWin.xaml

<Window x:Class="WPFDemo01.CustomColumnDataGridWin"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="Custom Column in DataGrid" Height="400" Width="450" Loaded="Window_Loaded"><Grid><DataGrid AutoGenerateColumns="False" Name="datagrid1" Margin="0,0,0,0" Width="430" Height="380"><DataGrid.Columns><DataGridTextColumn Header="Member ID" Width="100" Binding="{Binding Path=MemberID}"></DataGridTextColumn><DataGridTextColumn Header="First Name" Width="120" Binding="{Binding Path=FName}"></DataGridTextColumn><DataGridTextColumn Header="Alias Name" Width="120" Binding="{Binding Path=AliasName}"></DataGridTextColumn><DataGridTextColumn Header="Reg Date" Width="80" Binding="{Binding Path=Reg_Date,StringFormat={}{0:dd-MMM-yyyy}}"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid></Window>

In above code, I have added a new column call as RegDate, this is column has date if the registration, i have applied formatting to date “dd-MMM-yyyy” using StringFormat. In the code behind does not have any changes.

Output

Image Loading

Note: when you are specifying the columns in the Binding Path you have to very careful, because C# treats as column with case sensitive manner.
For example: Reg_Date is actual column in the database for above demo, if you are five reg_date under the Path its wont bind data to DataGrid.

Extras

How to format the currency

Just simple, you have to change the xaml code to currency column like following,

<DataGridTextColumn Header="Net Amount" Width="80" Binding="{Binding Path=netamount,StringFormat={}{0:C}}"></DataGridTextColumn>

Conclusion

I have given three different demonstration and sample to bind data in WPF with .NET Framework 4.0 using DataGrid Control.I hope, this is very helpful you all. Happy programming.

Sample Project Source

Download source files -67 kb

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
Comments
By:MikeDate Of Posted:11/21/2011 5:14:53 PM
Group
In your example, how would you group the first column?
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top