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.

<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.


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;
            }
        }
    }

}
Post a Comment