Thursday, 22 March 2012

Binding Collection to the DataGrid.

Hi .. This article is about binding the collection of data to the controls that display in a format like Table or list and etc..
It took so much time for me to understand the things behind binding the data using collections.So, i'm sharing my snippets for reference.
First of all, i have taken a Datagrid control .You can drag it from the ToolBox to bind the data.
<DataGrid Height="100" AutoGenerateColumns="False"HorizontalAlignment="Left" Margin="10,10,10,10" Name="dataGrid1" VerticalAlignment="Top" Width="200"/> 
After that i have created my collection of items to bind to the control in the MainWindow.cs page.Here, the list looks like,
public class Author
  {
    public int ID { get; set; }
    public string Name { get; set; }    
   }
private List<Author> LoadCollectionData()
  {
   List<Author> authors = new List<Author>();
      authors.Add(new Author(){ID = 101,Name = "Darren"});
      authors.Add(new Author(){ID = 201,Name = "Kathy"});
      authors.Add(new Author(){ID = 301,Name = "AJ"});
 return authors;
}
Now we have to bind these collection to the DataGrid that we have placed in our MainWindow.XAML.
For this we have to add the XML namespace assembly of the current project to make available of all the properties and methods to the controls that we work with.
I have added this as,
xmlns:loc="clr-namespace:ClassListBind"
Now we have to call the method of the list<Author> that we have created in the resources to make it available to the controls.
 <Window.Resources>
  <ObjectDataProvider x:Key="MyData" ObjectType="{x:Type      loc:DatatList}" MethodName="LoadCollectionData"/>                
</Window.Resources>
Here i have assigned a name for this to call where ever i need.And, i have added two columns to the datagrid to bind the data as needed.
After this i have called this static resource in the datagrid control's item source like this.
<DataGrid Height="100" AutoGenerateColumns="False" ItemsSource="{Binding Source={StaticResource MyData}}" HorizontalAlignment="Left" Margin="7,9,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200">
  <DataGrid.Columns>
   <DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
   <DataGridTextColumn Binding="{Binding ID}" Header="ID"/>
  </DataGrid.Columns>
</DataGrid>

Like this we have to bind the collection of items to the controls to display as we needed.
This is the article about binding. 
Hope you understand ..!!