Code Snippet 3: CustomerInfoCollection GetAllCustomers() method
public class CustomerInfo
{
private DataRow m_dr;
private CustomerInfoCollection m_cic;
public CustomerInfo(CustomerInfoCollection coll, DataRow dr)
{
m_cic = coll;
m_dr = dr;
}
}
Code Snippet 4: CustomerInfo Class & Constructor
Now, the DataRow object is associated with the DataTable in the Collection class as well as with an object. Now all we have to do is define properties which directly access the columns in the DataRow. In this way, we create a direct conduit into the DataSet and a way to centralise inserts, updates and deletes.
Here is an example:
public string CustomerID
{
get
{
if (m_dr["CustomerID"] == System.DBNull.Value)
return "";
else
return m_dr["CustomerID"].ToString();
}
set
{
m_dr["CustomerID"] = value;
}
}Implementing Business Rules
So where do those much-talked-about business rules go? Well, we've already implemented one called GetAllCustomers. So all we have to do is implement a Create and Update method:
To create a new Customer, we need to do 3 things:
1. Instantiate a new DataRow based on the Customer DataTable
2. Add the DataRow to the Rows collection of DataTable
3. Instantiate a new CustomerInfo object and add it to the collection.
We will also need our method to return the newly instantiated ClientInfo object so that we can use it in the Presentation Layer.
Here is the method we will implement in the CustomerInfoCollection class:
public CustomerInfo Create()
{
DataRow dr = m_ds.Tables["Customers"].NewRow();
m_ds.Tables["Customers"].Rows.Add(dr);
CustomerInfo ci = new CustomerInfo(this, dr);
this.Add(ci);
return ci;
}Code Snippet 6: CustomerInfoCollection Create() Method
Note that we have used the Add method instead of adding our object directly to the ArrayList; it is one of the methods you will need to write in order to implement IList.
To implement the update, it is even easier. Since every Info class feeds directly into the collection DataTable, all we have to do is send the entire DataSet to the Data Layer which will deal with the request. public void Update()
{
DCustomers cust = new DCustomers();
// No try/catch because the Exception will be passed to the calling object in
// the presentation layer
m_ds = cust.UpdateCustomers(m_ds);
}Code Snippet 7: CustomerInfoCollection Update() Method
So that was fairly easy. We now have to implement the Delete and, more importantly, the Undo methods.
Because we have a DataRow inside our CustomerInfo object, we need to be able to remove this object from the collection at the same time as we delete the row. We will also need to extend our CustomerInfo class and add a couple of helper properties, notably a Parent property which points back to the collection class (see Code Snippet 4) and a RowStatus property, which send back the DataRow Rowstate.
public CustomerInfoCollection Parent
{
get
{
return m_Parent;
}
}
public DataRowState RowStatus
{
get
{
return m_dr.RowState;
}
}