Search...

Friday, July 19, 2013

How to bind DataTable to DataGrid in WPF

Download

Step 1: Create a WPF application and update the MainWindow.xaml as follows.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<Window x:Class="BindDataTable.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataGridAndDataTable" Height="273" Width="721" Loaded="Window_Loaded">
    <Grid>
        <DataGrid Name="dataGridEmployee" AutoGenerateColumns="False" AlternatingRowBackground="#c2ccdb">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Id}" Header="Id" Width="80"/>
                <DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="200"/>
                <DataGridTextColumn Binding="{Binding Salary}" Header="Salary" Width="100"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

</Window>

Step 2: Update the MainWindow.cs as follows.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Data;
using System.Windows;

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

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.dataGridEmployee.ItemsSource = this.BindEmployee().DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private DataTable BindEmployee()
        {
            try
            {
                DataTable employee = new DataTable();
                employee.Columns.Add(new DataColumn("Id", Type.GetType("System.Int32")));
                employee.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
                employee.Columns.Add(new DataColumn("Salary", Type.GetType("System.Decimal")));

                int iterator = 0;

                while (++iterator < 101)
                {
                    DataRow row = null;
                    row = employee.NewRow();
                    row["Id"] = iterator;
                    row["Name"] = "Employee " + iterator;
                    row["Salary"] = ((9999 * iterator) * 5.6) / (iterator+1);
                    employee.Rows.Add(row);
                }
                return employee;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

No comments: