HOME PAGE | DOWNLOAD | TUTORIALS | XtraReports
Devexpress

Sunday, July 22, 2012

How to: Bind a Control to Data Created at Runtime

The following example demonstrates a way of binding an array of custom objects to the XtraGrid control.

Start by declaring a class to represent an individual record. The code below declares a class with ID, Name and Age public properties. These properties will be data source fields. Note that the ID property is declared as read-only. As a result, its associated column will also be read-only.

C#

public class Record {

   int id, age;

   string name;

   public Record(int id, string name, int age) {

      this.id = id;

      this.name = name;

      this.age = age;

   }

   public int ID { get { return id; } }

   public string Name {

      get { return name; }

      set { name = value; }

   }

   public int Age {

      get { return age; }

      set { age = value; }

   }

}

VB

Public Class Record
   Dim _id, _age As Integer 
   Dim _name As String 
   Public Sub New(ByVal id As Integer, ByVal name As String, ByVal age As Integer)
      Me._id = id
      Me._name = name
      Me._age = age
   End Sub 
 
   Public ReadOnly Property ID() As Integer 
      Get 
         Return _id
      End Get 
   End Property 
 
   Public Property Name() As String 
      Get 
         Return _name
      End Get 
      Set(ByVal Value As String)
         _name = Value
      End Set 
   End Property 
 
   Public Property Age() As Integer 
      Get 
         Return _age
      End Get 
      Set(ByVal Value As Integer)
         _age = Value
      End Set 
   End Property 
End Class 

Once the record class has been declared, the data source object can be filled with records. This example will use a BingingList<T> as the grid's data source.

The code below fills a BindingList<T> with records and assigns it to the grid's GridControl.DataSource property. By default, columns for all data source fields are created automatically.

C#
BindingList<Record> listDataSource = new BindingList<Record>();
listDataSource.Add(new Record(1, "Jane Parker", 19));
listDataSource.Add(new Record(2, "Joe Smith", 30));
listDataSource.Add(new Record(3, "Bill Quimby", 15));
listDataSource.Add(new Record(4, "Michael Simpson", 42));
gridControl1.DataSource = listDataSource;

VB

Dim listDataSource As New System.ComponentModel.BindingList(Of Record)
listDataSource.Add(New Record(1, "Jane Parker", 19))
listDataSource.Add(New Record(2, "Joe Smith", 30))
listDataSource.Add(New Record(3, "Bill Quimby", 15))
listDataSource.Add(New Record(4, "Michael Simpson", 42))
GridControl1.DataSource = listDataSource

 

The result of this code is shown below:

No comments:

Post a Comment