DataGrid In WPF

Here are the steps to create a DataGrid in WPF with AutoGenerated Columns and Selected Columns,

  1. Create a new WPF project.

    Click File, Project,  Windows, then WPF Application.

    WPF Application

  2. After creating project, a screen will get displayed like the following,

    creation of project

  3. Default Files,

    App.xaml: This file take care of Class and StartUri that is which window (form) you want to execute first. App.xaml is same as Program.cs file of WinForm application on functionality point of view.

    MainWindow.xaml: By default file created by visual studio for WPF app. This file as same as Form1.cs created default in WinForm for start to work on WPF.

    WPF mixture of Web, WinForm kind of coding and functionality. WPF form file having two way coding facility like WebForm having XAML tab or Design tab.

    WPF is elder brother of WinForm.

    DataGrid control available from Version 4.0 in Dot Net framework.

  4. Insert a DataGrid control from toolbox.

    Adjust size as you want. You can set size from code behind or through xaml code.

    Adjust size

Firstly, I am showing AutoGenerateColumns="True", then afterwards I will show AutoGenerateColumns="False". 

Before starting code behind things, first I am explaining you required namespaces for implementation of ADO.NET code to fill DataGrid.

For fetching connection string from APP.CONFIG we have to first give reference of System.Configuration.dll file.

Right click on Project name or Reference folder.

  1. Select Add Reference option.

    Add reference

While you click on Add Reference, Reference manager window will open.

Select Framework, the first option left side of window then search and select System.Configuration.

reference

After completion of reference, you can use System.Configuration namespace.

Namespace Required

Please, add the following namespace in code behind in this project using default file name MainWindow.xaml.cs.

Namespace Functionalities
Using System.Data To get ADO.NET data handling classes.
Using System.Data.SqlClient To connect to Microsoft SQL server.
Using System.Configuration To fetch configuration and connectionstring from app.config.

For implementing DataGrid, I used three files and table whose code is given below, 

Table Structure inside MemberCDAC database, table named tblFriends,

  1. USE [MemberCDAC]  
  2. GO  
  3. /****** Object:  Table [dbo].[tblFriends]    Script Date: 12/19/2015 09:48:03 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. SET ANSI_PADDING ON  
  9. GO  
  10. CREATE TABLE [dbo].[tblFriends](  
  11.     [FriendID] [int] IDENTITY(1,1) NOT NULL,  
  12.     [FriendName] [varchar](50) NULL,  
  13.     [FriendImage] [varchar](500) NULL,  
  14.     [Place] [varchar](500) NULL,  
  15.     [Mobile] [varchar](20) NULL  
  16. ON [PRIMARY]  
  17.   
  18. GO  
App.Config file:

 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2.    <configuration>  
  3.       <connectionStrings>  
  4.          <add name="MemberCDACConnectionString" connectionString="Data Source=SAIBABA-PC\SAIBABA;Initial Catalog=MemberCDAC;Integrated Security=True" providerName="System.Data.SqlClient"/>  
  5.       </connectionStrings>  
  6. </configuration>  
MainWindow.xaml file
  1.     <Window x:Class="FirstWpfApplication.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         Title="MainWindow" Height="500" Width="700">  
  5.     <Grid Margin="0,-4,0,4">  
  6.         <DataGrid HorizontalAlignment="Left" VerticalAlignment="Top" Height="174" Width="562" Margin="0,275,0,0"   
  7.          AutoGenerateColumns="True" Name="grdFriends"/>  
  8.   
  9.     </Grid>  
  10. </Window>  
MainWindow.xaml.cs file
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.SqlClient;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Windows;  
  8. using System.Windows.Controls;  
  9. using System.Windows.Data;  
  10. using System.Windows.Documents;  
  11. using System.Windows.Input;  
  12. using System.Windows.Media;  
  13. using System.Windows.Media.Imaging;  
  14. using System.Windows.Navigation;  
  15. using System.Windows.Shapes;  
  16. using System.Configuration;  
  17. namespace FirstWpfApplication  
  18. {  
  19.     /// <summary>  
  20.     /// Interaction logic for MainWindow.xaml  
  21.     /// </summary>  
  22.     public partial class MainWindow: Window  
  23.     {  
  24.         //To fetch connection string from APP.CONFIG file.  
  25.         string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
  26.         public MainWindow()  
  27.             {  
  28.                 InitializeComponent();  
  29.                 BindDataGrid();  
  30.             }  
  31.             //Binding DataGrid control with data.  
  32.         public void BindDataGrid()  
  33.         {  
  34.             //Set connection which feteched from app.config.  
  35.             SqlConnection con = new SqlConnection(ConStr);  
  36.             //SELECT query to fetch data from TBLFREINDS  
  37.             SqlDataAdapter da = new SqlDataAdapter("Select * From tblFriends", ConStr);  
  38.             //DataSet is virutual database or data container.  
  39.             DataSet ds = new DataSet();  
  40.             //Fill data inside ds(DataSet) with TableNamed FriendTable  
  41.             da.Fill(ds, "FriendTable");  
  42.             //Bind Data with DataGrid control.  
  43.             grdFriends.ItemsSource = ds.Tables["FriendTable"].DefaultView;  
  44.         }  
  45.     }  
  46. }  
menu

In above screen and example, I selected autogeneratedcolumn = true.

Next, you will learn how to set column in DataGrid control manually.

SELCTED COLUMN

Now, you will learn how to set columns inside DataGrid control.

MainWindow.xaml code:

In following code, I had manually set columns name. Some cosmetic changes to all columns in grid with FontSize, FontWeight,
  1. <Window x:Class="FirstWpfApplication.MainWindow"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     Title="MainWindow" Height="500" Width="700">  
  5. <Grid Margin="0,-4,0,4">  
  6.     <DataGrid HorizontalAlignment="Left" VerticalAlignment="Top" Height="174" Width="649" Margin="0,275,0,0"   
  7.      AutoGenerateColumns="False" Name="grdFriends">  
  8.         <DataGrid.Columns>  
  9.             <DataGridTextColumn Header="Friend ID" Width="100" Binding="{Binding FriendID}" FontSize="14" FontWeight="Bold" />  
  10.             <DataGridTextColumn Header="Friend Name" Width="300" Binding="{Binding FriendName}" FontSize="14" FontWeight="Bold"  />  
  11.             <DataGridTextColumn Header="Place " Width="100" Binding="{Binding Place}" FontSize="14" FontWeight="Bold"  />  
  12.             <DataGridTextColumn Header="Mobile" Width="100" Binding="{Binding Mobile}" FontSize="14" FontWeight="Bold"  />  
  13.         </DataGrid.Columns>  
  14.     </DataGrid>  
  15.   
  16. </Grid>  
  17. /Window>  
main window

 

Up Next
    Ebook Download
    View all
    Learn
    View all