Click here to Skip to main content
Click here to Skip to main content
Go to top

Data binding in WPF DataGrid control using SQL Server database

, 10 Apr 2012
Rate this:
Please Sign up or sign in to vote.
In this article I will explain how to display data from a SQL Server database table in a WPF DataGrid control

Introduction

Displaying data in a grid is a common task in a Windows application. In a Windows application we use the DataGridView control for this task. In WPF, we can use the DataGrid control for the same. In this article we will display the contents of the Employee table of the Pubs database in a WPF DataGrid control.

Using the code

Followings are the steps to achive the above task.

Step 1: 

Create a new WPF Application

Note: I am using Visual C# 2010 Express

Step 2:  

Add a new “Application Configuration File” with named “App.config” and your connection string

<configuration>
 <connectionstrings>
    <add connectionstring="Data Source=YourDataSource; User Id=YourUserName;Password=YourPassword; Initial Catalog=Pubs;" name="ConString"/>
 </connectionstrings>
</configuration> 

Step 3: 

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

Step 4:   

Add a DataGrid control in the MainWindow.xaml file.

<datagrid name="grdEmployee" />  


Write following code in MainWindow.xaml.cs to bind data.

public MainWindow()
{ 
    InitializeComponent();
    FillDataGrid(); 
}

private void FillDataGrid()
{ 
    string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    string CmdString = string.Empty;
    using (SqlConnection con = new SqlConnection(ConString))
    {
        CmdString = "SELECT emp_id, fname, lname, hire_date FROM Employee";
        SqlCommand cmd = new SqlCommand(CmdString, con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable("Employee");
        sda.Fill(dt);
        grdEmployee.ItemsSource = dt.DefaultView; 
    }  
}
Here first we loaded Employee database table in a DataTable object and then bind it to the DataGrid’s ItemsSource property.

Step 5:

After running the application we get the following output



ItemsSource does it all for us. It displays all the data from the underlying data source. But it has some limitations like you can see header of the columns are same as the database table column names. To give column’s header a user defined name you can change DataGrid definition as following code in MainWindow.xaml file

<datagrid alternatingrowremoved="#FFC4B0B0" height="400" width="350" autogeneratecolumns="False" name="grdEmployee">
    <datagrid.columns>
        <datagridtextcolumn binding="{Binding FirstName}" width="100" header="First Name"/>
        <datagridtextcolumn binding="{Binding LastName}" width="100" header="Last Name"/>
        <datagridtextcolumn binding="{Binding Salary}" width="100" header="Salary"/>
    </datagrid.columns>
</datagrid>

Final Output:  

 

Points of Interest

When we set ItemsSource property of a DataGrid to a data source, it displays all all the columns with its default name. To give a user defined name to the DataGrid columns we have to set AutoGenerateColumns="False" and define its columns explicitly.

History

  • 9 April, 2012.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Deepak_Sharma_
Software Developer (Senior)
India India
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

 
Suggestionhow about update that tbale by adding/deleting editing rows? Pinmemberstelios198417-Jul-14 21:04 
QuestionError PinmemberMember 1081830520-May-14 23:22 
QuestionConnection String PinmemberMember 1075352816-Apr-14 2:59 
Questionconfiguartion element is not declared PinmemberMember 1073299110-Apr-14 18:34 
QuestionConfiguration manager doesn't exist in current context PinmemberMember 107329918-Apr-14 0:39 
QuestionConnection manager PinmemberR.BinayRam3-Apr-14 2:41 
AnswerRe: Connection manager PinmemberDeepak_Sharma_4-Apr-14 6:10 
QuestionXamlParseException was unhandled error is coming PinprofessionalMember 1028454127-Nov-13 18:39 
QuestionThank you for sharing..But i have a question. PinmemberMember 1040682617-Nov-13 1:27 
QuestionGreat article for displaying the data.... but... PinmemberBogus Exception14-Oct-13 4:53 
AnswerRe: Great article for displaying the data.... but... PinmemberDeepak_Sharma_14-Oct-13 19:54 
GeneralRe: Great article for displaying the data.... but... PinmemberBogus Exception7-Mar-14 9:30 
General"Exception has been thrown by the target of an invocation." PinprofessionalMAYANK GEETE11-Sep-13 0:36 
GeneralGreat Article for getting started with WPF and the DataGrid [modified] PinmemberGuttorm Haaversen7-Sep-13 8:39 
GeneralRe: Great Article for getting started with WPF and the DataGrid PinmemberDeepak_Sharma_14-Oct-13 20:24 
QuestionError PinmemberAbhishek Durvasula4-Sep-13 19:33 
AnswerRe: Error PinmemberAbhishek Durvasula4-Sep-13 20:15 
QuestionDataTable PinmemberMember 101909725-Aug-13 8:42 
AnswerRe: DataTable PinmemberMember 101909725-Aug-13 9:04 
GeneralMy vote of 5 PinmemberMember 998831623-Jul-13 6:58 
SuggestionBinding names and case sensitivity PinmemberRickiB31-May-13 13:57 
QuestionScalar Query Pinmembermuralimahendra3-Oct-12 0:03 
Hi Deepak
 
It's a very nice example on showing the AutoGeneratedColumns="true" works.
If I send a query which returns a scalar value like
CmdString = "SELECT count(*) FROM Employee";
 
the result doesn't have any column name but only a result value which i have set to DataGrid ItemsSource, but it does show anything.
 
How do i show that result value in the DataGrid with some default column name.
 
Thanks in Advance
QuestionGreat, simple example... however, it generated an runtime error about ConfiguraitonManager... Pinmemberyoungtexas19-Apr-12 4:58 
AnswerRe: Great, simple example... however, it generated an runtime error about ConfiguraitonManager... PinmemberDeepak_Sharma_19-Apr-12 5:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 10 Apr 2012
Article Copyright 2012 by Deepak_Sharma_
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid