Binding DataGrid in WPF

Raj.Trivedi
Posted by in WPF category on for Beginner level | Points: 250 | Views : 21970 red flag

Hello Friends,

In this article we will see how we can bind datagrid in WPF.Though it might seem easy but there are some important properties that we need to understand.

Introduction


Couple of days back me and my friends were talking about WPF i.e. Windows Presentation Foundation which is introduced by Microsoft in .NET Framework 3.5.

There were some confusions and after the discussion i realized that there is a fear in working with WPF.

So lets get the fear out.

This article is basically for beginners in WPF.



Objective

  1. Binding Data Grid in WPF
  2. Adding Columns in Data Grid
  3. Understanding ItemSource Property



Using the code


  1. Open VS2010 -> Create New Project -> Select New WPF Application.
  2. Now Go to the Toolbox and drag a Data Grid
  3. Now its time to add Columns.
  4. To give the Header to the columns use the Header property of the column.
  5. Now to add the Column we will have to write the code in XAML design.(Check the Screen 3)
  6. XAML is nothing but a place where you write the design logic as we do in .aspx page.In aspx we use HTML but in XAML it is an XML based Language used for designing.Full form of XAML is Extensible Application Markup Language


Step :1





Step 2






Step 3




The code highlighted is the code that to add columns in datagrid.

Now we will see how to bind the data grid

Firstly we need to assign the Binding property in XAML file to each column.The Binding Property works as DataBound property of ASPX Grid.The Binding property will actually assign the data to the column.

ItemSource Property

This property will take the object of the data-set or data table to bind the data to the grid.But over here there is one trick that we need to understand that just assigning the object of data-set is not going to work because Itemsource is an I Enumerable type and that cannot be implicitly converted to data-set and hence we need to assign the table and default view of the data-set.

There is no rocket science in Code behind Logic it is just a normal Logic Written to get data from Data Base using Stored Procedure.


// Table and Stored Procedure
USE [DNF]
GO

/****** Object:  Table [dbo].[People]    Script Date: 07/04/2013 23:00:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[People](
	[ID] [int] NOT NULL,
	[Name] [varchar](50) NOT NULL,
	[City] [varchar](50) NOT NULL,
	[Pincode] [int] NOT NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

USE [DNF]
GO

/****** Object:  StoredProcedure [dbo].[GetPeople]    Script Date: 07/04/2013 23:00:35 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc [dbo].[GetPeople]
as
begin
select * from People
end
GO


//XAML File.
<Window x:Class="DataGridWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <Label Content="Binding Data Grid in WPF" Height="28" HorizontalAlignment="Left" Margin="170,24,0,0" Name="label1" VerticalAlignment="Top" Width="168" ></Label>
        <DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="101,83,0,0" Name="Xgrid" VerticalAlignment="Top" Width="330">
                  <DataGrid.Columns>
                 
                <DataGridTextColumn Header="ID" Width="50" Binding="{Binding ID}"></DataGridTextColumn>
                <DataGridTextColumn Header="Name" Width="100" Binding="{Binding Name}"></DataGridTextColumn>
                <DataGridTextColumn Header="City" Width="100" Binding="{Binding City}"></DataGridTextColumn>
                <DataGridTextColumn Header="PinCode" Width="75" Binding="{Binding Pincode}"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>
//Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;

namespace DataGridWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Connecting the SQL Server
                SqlConnection con = new SqlConnection("Data Source=AG-KKC;Initial Catalog=DNF;Persist Security Info=True;User ID=sa;Password=sqluser");
                con.Open();
                // Calling the Stored Procedure
                SqlCommand cmd = new SqlCommand("GetPeople", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    // Binding the Grid with the Itemsource property
                    Xgrid.ItemsSource = ds.Tables[0].DefaultView;
                }
                con.Close();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                
            }
        }

        
    }
}
Final Output






Conclusion


I hope after reading this Article WPF fear will come out from beginners.



Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)