IntroductionThis 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 1Create WPF application using visual studio 2010. Step 2Once you are created WPF project, then you will see like following, Step 3Then remove the Grid xaml tags from the window, and drag and drop the DataGrid control from the toolbox and place inside the design surface. 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 ColumnsFirst 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 Step 6: Define ColumnsIn 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 Step 7:Format coumnsUse 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 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. ExtrasHow to format the currencyJust 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>ConclusionI 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 SourceDownload source files -67 kb |