Monday, June 23, 2008

Performing Insert, Update and Delete using ObjectContainerDataSource

It is very easy and effective to use ObjectContainerDataSource to handle insert, update and delete event. When the user performs an update operations, insert operation, or delete operation in a data-bound control, the data source control raises the following events.

C#

public event EventHandler Updated;
public event EventHandler Inserted;
public event EventHandler Deleted;

For example, if you are using DetailsView and ObjectContainerDataSource in your page to create a Insert form,

1.) Named your ObjectContainerDataSource, like MemberDataSource
2.) Set your DataObjectTypeName.
3.) Named your Details View, like dvCreateMember
4.) Set the DataKeyNames="id" in Details View, most of the time it should be the primary key.
5.) Set the DataSourceID="MemberDataSource" Details View
6.) Set the DefaultMode="Insert" in Details View
7.) In the ObjectContainerDataSource, set the OnInserted event name.

Codes will look like this:-


<div>
<asp:DetailsView ID="dvCreateMember" DataKeyNames="id" DefaultMode="Insert" runat="server" AutoGenerateRows="False" DataSourceID="MemberDataSource">
<Fields>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="age" HeaderText="Age" SortExpression="age" />
<asp:CommandField ButtonType="Button" InsertText="Create" NewText="Add New" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
<br />
</div>
<pp:ObjectContainerDataSource ID="MemberDataSource" runat="server" DataObjectTypeName="Repository.BusinessEntities.member" OnInserted="MemberDataSource_Inserted" />
In the Code Behind Page, the event handler function will look like this:-


using Microsoft.Practices.Web.UI.WebControls;

protected void MemberDataSource_Inserted(object sender,
ObjectContainerDataSourceStatusEventArgs
e)
{
_presenter.onCreateMember((member)e.Instance);
}


The data that inserted into the details view will be automatically stored into the e.instance when it is passed to ObjectContainerDataSource. Hence, there is no need to have extra code to map the data from UI to back end codes.

Noticed that there is a function onCreateMember() being called in the Inserted event. It is the function defined in Presenter Layer.

### Presenter Class File###


public void onCreateMember(member
obj)
{
_controller.CreateMember(obj);
}

And, CreateMember() function is defined in Controller layer.

###Controller Class File###


public void CreateMember(member obj)
{
_member = new memberRepository();
_member.Add(obj);
}

In the above function, it is call the add function from Data Access layer. You may use Repository Factory to generate those.

1 comment:

Jen said...

The blog is helpfull...
visit also asp.net [c#]