Sometimes we may have requirement like holding the instances of particular class type. We can do this in C# by using System.Collection.Generic namespace. You can hold instances of class by using ArrayList also, but ArrayList holds any type of data. So, by using List types we can create type safe container.
For example you have a class named Employee with two public properties Id, Name as shown below.
public class Employee
{
public Employee()
{
}
public int Id { get; set; }
public string Name { get; set; }
}
You can create custom List of Employee class type easily by using System.Collection.Generic.List<T> as shown below.
using System;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Employee> list = new List<Employee>();
Employee obj1 = new Employee();
obj1.Id = 1;
obj1.Name = "A";
Employee obj2 = new Employee();
obj2.Id = 2;
obj2.Name = "B";
Employee obj3 = new Employee();
obj3.Id = 3;
obj3.Name = "C";
list.Add(obj1);
list.Add(obj2);
list.Add(obj3);
gv1.DataSource = list;
gv1.DataBind();
}
}
As shown above, we are importing the System.Collection.Generic Namespace. First create object of List<Employee> and add each class instance to that list. Then you can bind this list to Gridview control or Listview control.