Collection with ObjectDataSource : Parameters « Data Binding « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ObjectDataSource" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ObjectDataSource</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ObjectDataSource ID="ObjectDataSource1" 
                              runat="server" 
                              DataObjectTypeName="Customer" 
                              DeleteMethod="Delete" 
                              InsertMethod="Add" 
                              SelectMethod="GetCustomers" 
                              TypeName="CustomerData" 
                              UpdateMethod="Update" 
                              SelectCountMethod="Count">
            <UpdateParameters>
                <asp:Parameter Name="customerID" Type="Int32" />
                <asp:Parameter Name="firstName" Type="String" />
                <asp:Parameter Name="lastName" Type="String" />
                <asp:Parameter Name="address" Type="String" />
                <asp:Parameter Name="city" Type="String" />
                <asp:Parameter Name="state" Type="String" />
            </UpdateParameters>
        </asp:ObjectDataSource>
        &nbsp;
        <asp:GridView ID="GridView1" 
                      runat="server" 
                      AutoGenerateColumns="False"
                      DataSourceID="ObjectDataSource1" 
                      CellPadding="4" 
                      ForeColor="#333333" 
                      GridLines="None">
            <Columns>
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" SortExpression="CustomerID" />
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

[Serializable]
public class Customer
{
    private int customerID;
    public int CustomerID
    {
        get { return customerID; }
        set { customerID = value; }
    }
    private string firstName;
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    private string lastName;
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    private string address;
    public string Address
    {
        get { return address; }
        set { address = value; }
    }

    private string city;
    public string City
    {
        get { return city; }
        set { city = value; }
    }

    private string state;
    public string State
    {
        get { return state; }
        set { state = value; }
    }

    public Customer()
    {
    }

  public Customer(int customerID, 
        string firstName, 
        string lastName, 
        string address, 
        string city, 
        string state)
  {
        this.CustomerID = customerID;
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Address = address;
        this.City = city;
        this.State = state;
    }
}

public class CustomerData
{
    public CustomerData()
    {
        if (Customers.Rows.Count == 0)
        {
            FetchCustomers();
        }
    }

    public void Update(int customerID,
        string firstName,
        string lastName,
        string address,
        string city,
        string state)
    {
        Customer c = Get(customerID);

        c.CustomerID = customerID;
        c.FirstName = firstName;
        c.LastName = lastName;
        c.Address = address;
        c.City = city;
        c.State = state;
    }

    public IEnumerable<Customer> GetCustomers()
    {
        foreach (DataRow row in Customers.Rows)
            yield return CustomerFromRow(row);
    }

    public List<Customer> GetCustomers(int rows, int startIndex)
    {
        if (rows == 0) rows = Customers.Rows.Count;
        List<Customer> pageCustomers = new List<Customer>();
        for (int i = startIndex; i <= rows && i <= Customers.Rows.Count - 1; i++)
            pageCustomers.Add(CustomerFromRow(Customers.Rows[i]));
        return pageCustomers;
    }

    public Customer Get(int id)
    {
        return FetchCustomerById(id);
    }

    public void Add(Customer c)
    {
        Customers.Rows.Add(
            c.CustomerID,
            c.FirstName,
            c.LastName,
            c.Address,
            c.City,
            c.State
            );
    }

    public void Delete(int id)
    {
        DataRow[] rows = Customers.Select("CustomerID = " + id);
        if (rows.Length == 1)
            Customers.Rows.Remove(rows[0]);
    }

    public void Delete(Customer c)
    {
        Delete(c.CustomerID);
    }

    public int Count()
    {
        return Customers.Rows.Count;
    }

    private void FetchCustomers()
    {
        string[] First = new string[] {"A", "B", "C", "D", "E" };
        string[] Last = new string[] { "F", "G", "H", "I", "J" };

        Random rng = new Random(Guid.NewGuid().GetHashCode());
        for (int i = 1; i < 50; i++)
            this.Add(
                new Customer(
                i, First[rng.Next(5)],
                Last[rng.Next(5)],
                rng.Next(1000) + " St.",
                "Dallas",
                "TX"));
    }

    private Customer FetchCustomerById(int id)
    {
        DataRow[] rows = Customers.Select("CustomerID = " + id);
        if (rows.Length == 1)
        {
            return CustomerFromRow(rows[0]);
        }
        return null;
    }

    private Customer CustomerFromRow(DataRow row)
    {
        Customer c = new Customer(
            int.Parse(row["CustomerID"].ToString()),
            row["FirstName"].ToString(),
            row["LastName"].ToString(),
            row["Address"].ToString(),
            row["City"].ToString(),
            row["State"].ToString()
            );
        return c;
    }

    private DataTable Customers
    {
        get
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            DataTable dt = context.Session["CustomerData"] as DataTable;
            if (context.Session["CustomerData"] as DataTable == null)
            {
                context.Session["CustomerData"] = CreateCustomerTable();
            }
            return context.Session["CustomerData"] as DataTable;
        }
        set
        {
            System.Web.HttpContext.
                Current.Session["CustomerData"] = value;
        }
    }

    private DataTable CreateCustomerTable()
    {
        DataTable dt = new DataTable("Customers");
        dt.Columns.Add("CustomerID", typeof(Int32));
        dt.Columns.Add("FirstName", typeof(string));
        dt.Columns.Add("LastName", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("City", typeof(string));
        dt.Columns.Add("State", typeof(string));
        return dt;
    }
}
public partial class ObjectDataSource : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}








19.22.Parameters
19.22.1.Using ASP.NET Parameters with DataSource Controls
19.22.2.Collection with ObjectDataSource