Working with DataGrid in WPF

Adding DataGrid control on your WPF project is as simple as dragging in the control and setting the ItemSource property to the list of objects.

but before you can do that you need to make sure that your project
"Target framework" is .NET Framework 4 or above and not .NET Framwork 3.5
you can simply change this by going to the project property and change the "Target framework" to .NET Framework 4

after that you can add the DataGrid Control on you WPF form, also make sure that you set the AutoGenerateColumns property to true.
I created a class Person and just populate a list of Persons and setting the datagrid.ItemSource property to the list of person.

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;

namespace WpfApplication2
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List persons = new List();

            persons.Add(new Person() { FirstName="John", LastName="Doe", Age = 36, Address="12313 some address" });
            persons.Add(new Person() { FirstName = "Dolores", LastName = "Doe", Age = 23, Address = "12313 some address" });
            persons.Add(new Person() { FirstName = "Roxanne", LastName = "Doe", Age = 26, Address = "12313 some address" });
            persons.Add(new Person() { FirstName = "Robert", LastName = "Doe", Age = 31, Address = "12313 some address" });

            this.dataGrid1.ItemsSource = persons;
        }
    }


    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }
}

note: if the ItemSource does not refresh when you do some changes on your collection then call dataGrid.Items.Refresh()

Leave a Reply

Proudly powered by Blogger
Theme: Esquire by Matthew Buchanan.
Converted by LiteThemes.com.