Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a method that returns List<employee> to a gridview

Tags:

.net

.net-3.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?

like image 688
acadia Avatar asked Aug 03 '10 18:08

acadia


2 Answers

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.

like image 148
JonH Avatar answered Nov 06 '22 02:11

JonH


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!

like image 5
Mitchel Sellers Avatar answered Nov 06 '22 03:11

Mitchel Sellers