Tuesday, January 15, 2013

Simple Example WPF DATA Grid:



 
    The DataGrid is commonly used window form control,when we try to learn WPF better to learn by actual 
starting with something we can relate with like datagrid control.
below is quick way to use datagrid in wpf.

Here I am binding grid to a Generics based collection.Latter on we will move to bind grid with data from sql server and xml using LINQ to  xml or linq to sql.

Generics in csharp  is somewhat  similar to templated class in C++.

Create a wpf application .add a class to it name it student.cs

Create a class here as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WpfControlDemo.Entity
{
    public class Student
    {

    public int id { get; set; }

    public string Fname { get; set; }

    public string Lname { get; set; }

    public DateTime AdmissionDate { get; set; }

    public string Gender { get; set; }

    private int Rating { get; set; }

    public bool NeedPlacement { get; set; }

    }
}

Now go to your MainWindow.xaml
Right click on here and select “view code”, in code window add this method to class
private List<Student> LoadCollectionData()
        {

            List<Student> Students = new List<Student>();

            Students.Add(new Student()
            {

                id = 1,
                Fname = "sangram",
                Lname = "desai",
                AdmissionDate = new DateTime(1975, 2, 23),
                Gender = "Male",
                NeedPlacement = true
            });

            Students.Add(new Student()
            {
                id = 2,
                Fname = "sagar",
                Lname = "desai",
                AdmissionDate = new DateTime(1982, 4, 12),
                Gender = "Male",
                NeedPlacement = true

            });

            Students.Add(new Student()
            {

                id = 3,
                Fname = "sachin",
                Lname = "desai",
                AdmissionDate = new DateTime(1982, 5, 12),
                Gender = "Male",
                NeedPlacement = false

            });
            Students.Add(new Student()
            {

                id = 4,
                Fname = "mayuri",
                Lname = "shirvankar",
                AdmissionDate = new DateTime(1982, 5, 12),
                Gender = "Female",
                NeedPlacement = true

            });

            Students.Add(new Student()
            {

                id = 5,
                Fname = "kirti",
                Lname = "shirvankar",
                AdmissionDate = new DateTime(1982, 5, 12),
                Gender = "Female"

            });

            return Students;

        }
You may get an error as student class is not available add

using WpfControlDemo.Entity;

in proper place

This method create a collection of student using Generics.

Now switch to design view of MainWindow.xaml add a DataGrid I am naming it as ‘dg1
And add a button my button name is LoadData1

Then change content property of Button to “Load data”,now click the button to generate corresponding event handler LoadData1_Click in code window of MainWindow.xaml

<Window x:Class="WpfControlDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="496">

    <Grid Height="331" Width="628">
       <DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left"     
       Margin="10,10,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" />

      <Button Content="LoadData" Height="23" HorizontalAlignment="Left"  
      Margin="213,221,0,0" Name="LoadData1" VerticalAlignment="Top" Width="75"    
      Click="LoadData1_Click" />
</Grid>
</Window>


Now modify your event handler for button click like follows
  private void LoadData1_Click(object sender, RoutedEventArgs e)
        {
            dg1.ItemsSource = LoadCollectionData();
        }

By default DataGrid’s auto generate column property is false set it to true so that datagrid markup look like
    <Grid Height="331" Width="628">
       <DataGrid AutoGenerateColumns="True" Height="200" HorizontalAlignment="Left"     
       Margin="10,10,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" />

Compile code and run Here you observe that all public properties of student  get bind in datagrid.
You can resize column width,sort rows,re arrange column order by dragging columns select a row at a time all these are due to default grid properties that one can customize using it’s attributes

<DataGrid AutoGenerateColumns="True" Height="185" HorizontalAlignment="Left" Margin="10,10,0,0" Name="dg1" VerticalAlignment="Top" Width="460" RowHeight="30" ColumnWidth="90" GridLinesVisibility="Vertical" HeadersVisibility="All" Background="LightGray"
        RowBackground="LightYellow" BorderBrush="Gray" BorderThickness="5" AlternatingRowBackground="LightBlue" IsReadOnly="True" CanUserReorderColumns="False"
        CanUserResizeColumns="False" CanUserSortColumns = "False" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" SelectionMode="Extended"/>

Here I set  SelectionMode  to Extended so that one can select more than just a row. We used RowBackground & AlternatingRowBackground pair of attribute to give different background color to alternate rows.Other relevant properties are Height,Width.
BorderBrush is border color in asp.net sense while BorderThickness is Border width.
CanUserReorderColumns is used to prevent user from re arranging columns in grid by dragging one over other. CanUserResizeColumns is used to prevent user from resizing column width.
Same way we can restrict user from sorting column by adding CanUserSortColumns=’False’

There are lot of attributes of datagrid that we can use to customize look and fill & it's behaviour.

 

No comments:

Post a Comment