Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment


Locations of visitors to this page


Latest Articles


Move to top
Working with silver light datagrid
Posted By Sarin on Oct 14, 2012     RSS Feeds     Latest Hinduism news
4108 Views

This article will give you a brief insight on how to use basic features of silverlight datagrid. Similar to asp.net gridview, silver light data grid allows you to show data in rows and columns.  However it has much more inbuilt UI features which makes it a better replacement of default asp.net grid view.
Declare datagrid
In order to use datagrid, you need to import System.Windows.Controls namespace.  
  
Simply drag and drop the datagrid control or add the following line at the top of xaml file to add a reference to window control namespace.
 
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"

Note: Dragging and dropping the datagrid control automaticaaly add a reference at the top of xaml file.
  
Then, show your datagrid on the xaml page. Simple datagrid can be declared as
 
<data:DataGrid x:Name="dg" Width="400" Height="300”>           
</data:DataGrid>
 
 
Data Binding
Bind the itemsource property of datagrid to any data source that implement iEnumerable. Each row of the datagrid would be bound to your data source object and each column would be bound to the property of your data source object.
For example, let us consider a simple example of loading an array of letters as a column of the datagrid.

dg.ItemsSource = "Mon Tue Wed Thu Fri Sat Sun".Split();
 
Output of this code is


Here each row is bound to the string object and a single column is shown with name string
  
Now let us consider a case of loading datagrid with collection of data. For this, I have created a class with some properties as shown below
public class Data
     {
        public string FirstName  get; set;
        public string LastName  get; set;
        public int Age  get; set;
        public bool Available  get; set;
        public DateTime DOJ  get; set;
     }
Now we will create a collection of this data class in a loaddata() method as
private List<Data> LoadData()
         {
            List<Data> crics = new List<Data>();
            crics.Add(new Data()
             {
                FirstName = "Mahi",
                LastName = "Dhoni",
                Age = 31,
                Available = false,
                DOJ = new DateTime(2001, 11, 10)
            });
            crics.Add(new Data()
             {
                FirstName = "Sarin",
                LastName = "Mall",
                Age = 26,
                Available = true,
                DOJ = new DateTime(2011, 05, 07)
            });
            crics.Add(new Data()
             {
                FirstName = "Sachin",
                LastName = "Tendulkar",
                Age = 39,
                Available = true,
                DOJ = new DateTime(1989, 01, 08)
            });
            crics.Add(new Data()
             {
                FirstName = "Viru",
                LastName = "Sehwag",
                Age = 34,
                Available = true,
                DOJ = new DateTime(1998, 01, 26)
            });
            return crics;
        }
    }
Let us now bind this collection to our datagrid
 dg.ItemsSource = LoadData();
  
Now on running the project, my datagrid looks like:

Manual column declaration and binding
As you see in the above figure, each of my datagrid row represent “data” class and each column “property” of “data” class. This is done automatically by the silverlight runtime when AutoGenerateColumns property is set to true.  
In case if you want to display only some property and hide the others or you want to do some formatting on the bound data, then we should consider manually adding the columns as

  <data:DataGrid x:Name="dg" Height="200" Width="600">
   <data:DataGrid.Columns>
     <data:DataGridTextColumn Header="First Name" Binding="Binding FirstName" />
     <data:DataGridTextColumn Header="Last Name" Binding="Binding LastName" />
     <data:DataGridTextColumn Header="Age" Width="50" Binding="Binding Age" />
     <data:DataGridCheckBoxColumn Header="Available" Binding="Binding Available" />
     <data:DataGridTextColumn Header="Date oj Joining" Binding="Binding DOJ" />
   </data:DataGrid.Columns>
</data:DataGrid>
As shown above, all columns are manually bounded to data class
DataGrid Column Types
Many types of columns can be bound to the datagrid. Some of the column types are:
  DataGridTextBoxColumn -This is the standard default column internally using a TextBlock to display data, and TextBox for editing data.  
      
  • DataGridCheckBoxColumn - DataGridCheckBoxColumn is a read-only checkbox for displaying Boolean value.  This column internally derives from DataGridBoundColumnBase class and is used as a template for building our own column types.
  •  DataGridTemplateColumn - This allow us to define any types of control or any number of controls inside the column.
         Column Properties:
      
  • CanUserResize - This property defines whether the columns can be resized.
          
  •  IsReadOnly - Determines if the column can be edited.  
  • Width - Sets the width of the column.  This value overrides the columnwidth property of datagrid.
  • Visibility - Hides or shows this column.
  • MinWidth - Sets the minimum width for this column.
        Setting Row Height and Column Width
    Silverlight automatically adjust row height and column width according to the data that fit into the columns, if the data is long then width of the column is increased and if data is short then the column width is decreased.
    In case if you want to have a uniform row height and column width then set the column width  and row height property of  
      
    The ColumnWidth and RowHeight property of DataGrid are used to set the column width and row height respectively
    <data:DataGrid x:Name="McDataGrid" Width="580" Height="270"
    ColumnWidth="100" RowHeight="40"/>           
       

    Similarly, we have the MaxHeight and MaxWidth property to set the maximum height and maximum width respectively.  We also have the MinColumnWidth and MaxColumnWidth properties represent the minimum width and maximum width of columns respectively.
    Grid Header and Grid Lines Visibility
     GridLinesVisibility property is used to define if you want to show horizontal, vertical grid lines or both. HeaderVisibility property is used to show or hide row and column headers.
    Following property change in datagrid will hide the header row and would show both vertical and horizontal grid lines code snippet makes vertical grid lines visible and header visible for both rows and columns.
    GridLinesVisibility="All" HeadersVisibility="None" 

    The new DataGrid looks like Figure 6.
    Grid Row Background color
    The Background,  RowBackground and AlternatingRowBackground Property are used to set the background of datagrid, datagrid row and datagrid alternate row respectively.
    Following property change in datagrid will change the default background color of grid and its rows to the color set in the property.  
    Background="LightGray"  RowBackground="LightBlue"                      AlternatingRowBackground="AliceBlue"
      
    The new DataGrid looks like

    Border Color and Thickness
    Similarly, Border thickness and color can be set using the BorderThickness and BorderBrush property. Following property change set the border color to gray and thickness to 5
    BorderBrush=Yellow" BorderThickness="5"
    The new DataGrid looks like

    Scrolling
    If you have huge number of records and many columns that the datagrid all columns  doesn’t fit in the screen then you can use the VerticalScrollBarVisibility and HorizontalScrollBarVisibility property to true. This property has four values - Auto, Disabled, Hidden, and Visible with the default value being auto which means, scrolling is enabled only if needed otherwise  hidden.
    The following code change enables the vertical and horizontal scrollbars.  
    HorizontalScrollBarVisibility="Visible"
    VerticalScrollBarVisibility="Visible"

    Notice the disabled horizontal and vertical scroll bar. Since my datagrid is big enough to fit all the columns and rows, scroll bars are shown in disabled mode.
      
    Sorting
    Sorting is enabled by default. To disable sorting, simply set the CanUserSortColumns property to false. The following code snippet sets CanUserSortColumns properties to false.
    CanUserSortColumns = "False"
    Summary
    In this article, we learnt how to use a DataGrid control in Silverlight.  

    Dowload Source Code
  • Note: Images used on this website are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

    Share this to your friends. One of your friend is waiting for your share.
    Related Articles
    Hide or unhide data using Visibility ValueConverter class
    Working with Grid control in silverlight
    Demo of Jquery functions and events for dropdownlist
    Working with Stack Panel in silverlight
    Call Codebehind method from GridView ItemTemplate Eval function
    Changing Grid View header and footer at run time
    Displaying Image in silverlight Datagrid
    Delete duplicate records from table in SQL
    How music affects plant growth
    create new controls in grid view at runtime

    Post Comment