5

I have method in my N-layered application that returns List<Employee>. Below is the sample code for the method:

public List<Employee> GetAllemployees()
{
    return DAL.GetEmployees();
} 

I have a GridView in my aspx page. How do I set the GridView's datasource as GetEmployees() so that all the employees are listed in the GridView?

Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
acadia
  • 2,301
  • 10
  • 40
  • 57

2 Answers2

7
myGrid.DataSource = GetAllEmployees();
myGrid.DataBind();

One thing worth mentioning, do you really want to create an employee object just to retrieve all employees?

I would do it like this:

public static List<Employee> GetAllEmployees()
{
    return myList;
}

And in your calling code:

MyGrid.DataSource = EmployeeClass.GetAllEmployees();
MyGrid.DataBind();

In this way you do not have to instantiate an object that simply gets a list of the object.

Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
JonH
  • 32,732
  • 12
  • 87
  • 145
5

Just like any other bindings, the result of the method call is the datasource, then call "DataBind". My example below assumes an instance of your class that contains the "GetAllEmployees" method that is called MyClass.

  GridView1.DataSource = myInstance.GetAllEmployees();
  GridView1.DataBind();

That is it!

Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173
  • He's assuming a static method `GetAllEmployees()` of a class called `MyClass` – JonH Aug 03 '10 at 18:58
  • Ahh he made an edit to use an instance rather then a static method. The instance is now myInstance and method is GetAllEmployees. See the edit log to see the original thread. – JonH Apr 06 '11 at 13:38