kennedy

A blog for blog-haters, by a blog-hater


Session 6 - Student Questions 

Tags: Session 6, Student Questions, All

Binding to a Collection of Custom Objects
 
This is relatively easy.  If we have a class that contains properties that expose values, we can quickly and easily bind a collection/array of those objects to a bindable control.
 
Let's say this is our custom class:
public class Employee
{
    int _EmployeeID;
    public int EmployeeID
    {
        get { return _EmployeeID; }
        set { _EmployeeID = value; }
    }
    string _EmployeeName;
    public string EmployeeName
    {
        get { return _EmployeeName; }
        set { _EmployeeName = value; }
    }
    public Employee(int EmployeeID, string EmployeeName)
    {
        this.EmployeeID = EmployeeID;
        this.EmployeeName = EmployeeName;
    }
}
 
Elsewhere in our code, we can create an array or collection of that type, and initialize instances of the Employee class to put in that array/collection.
 
Then we can assign the array/collection to the DataSource property of our GridView (for example) and call the DataBind method.
    protected void Page_Load(object sender, EventArgs e)
    {
        Employee[] emp = new Employee[3];
        emp[0] = new Employee(324, "hank");
        emp[1] = new Employee(123, "ralph");
        emp[2] = new Employee(321, "george");
        
        GridView1.DataSource = emp;
        GridView1.DataBind();
    }
 
We can then view that in the browser.
Array of objects bound to GridView
If we wished, in the Design view, we could Edit Columns and create two BoundFields, defining the HeaderText and DataField, and unselect Auto-generate fields, to display the data in a custom manner.
Custom Fields/Columns
Upon viewing in in the browser, it should look something like this:
Custom Fields
 
If we had another class that returned an array of generated objects, then this could be called via an ObjectDataSource control, meaning we could achieve the whole thing without manually writing code in the web form.
 
 
Page and Global.asax events sequence
 
Posted by Stephen Kennedy on 27-Nov-07
0 Comments  |  Trackback Url  |  Link to this post | Bookmark this post with:        
 

Comments

Name

Url

Email

Comments