Friday, April 11, 2008

Binding ArrayList with DataGrid

I will discuss how to create an ArrayList of objects and bind it to a DataGrid control using DataSource property.

Step 1. Creating a Class

First step is to create a class. I call my class Developer, which is listed in Listing 1. It's properties are FirstName, LastName, Age, Skills, and Experience.

public class Developer

{
private string firstName;
private string lastName;
private int age;
private string skills;
private int experience;
public Developer(string firstName, string lastName, int age, string skills, int experience )
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.skills = skills;
this.experience = experience;
}
/// First Name
public string FirstName
{
get { return this.firstName ; }
}
/// Last Name
public string LastName
{
get { return this.lastName ; }
}
/// Age
public int Age
{
get { return this.age ; }
}
/// Skill set
public string Skills
{
get { return this.skills ; }
}
/// Number of year experience

public int Experience
{
get { return this.experience ; }
}
}

Listing 1. Developer class

Step 2. Creating an ArrayList of Objects

Now next step is to create an ArrayList object of Developer class. Listing 2 adds 6 items to the ArrayList.

private ArrayList GetList()

{
ArrayList list = new ArrayList();
list.Add(new Developer("Mahesh", "Chand", 30, "C#,ASP.NET,Windows Forms", 10)) ;
list.Add(new Developer("Michael", "Gold", 35, "GDI+, ASP.NET", 15)) ;
list.Add(new Developer("Bhasker", "Das", 26, "VB.NET, Web Applications", 4)) ;
list.Add(new Developer("Ashish", "Singhal", 24, "ADO.NET, GDI+", 4)) ;
list.Add(new Developer("Neel", "Beniwal", 3, "C#,ASP.NET,Windows Forms", 0)) ;
list.Add(new Developer("Melanie", "Talmadge", 25, "Java", 2)) ;
return list;
}

Listing 2. ArrayList of Developer

Step 3. Binding with DataGrid

Now we can bind our ArrayList using DataGrid.DataSource property and DataGrid would understand what to display in its columns. The following code binds the ArrayList to DataGrid.

ArrayList list = GetList();

dataGrid1.DataSource = list;


Step 4. The Result

Now if I run my application, the output in DataGrid looks like Figure 1.


2 comments:

Inspiron said...

Thank you ......... so much..


SA28--

arcellgonzalez said...

Array is the most important function in programming language for me. Data grid menu is easy to build but binding array list with data grid is little bit difficult for me. But I have done successfully with your help.
yoga clothing