Using the GenericDataSource With Data Bound Controls
The GenericDataSource may be used just as the other ASP.NET DataSource controls: just register the control assembly, add the control in the ASP.NET mark-up and implement the proper Event Handlers:
- SelectHandler
- InsertHandler
- UpdateHandler
- DeleteHandler
Register the Control Assembly
<%@ Register Assembly="GenericDataSourceControl" Namespace="GenericDataSourceControl" TagPrefix="cc1" %>
Add the GenericDataSource Control in ASP.NET Mark-up
Additionally, register the control Event Handlers from the Mark-up, though this may be done more easily from the OnInit event.
<cc1:GenericDataSource ID="GenericDataSource1" runat="server"
OnSelectHandler="GenericDataSource1_SelectHandler"
OnInsertHandler="GenericDataSource1_InsertHandler"
OnUpdateHandler="GenericDataSource1_UpdateHandler"
OnDeleteHandler="GenericDataSource1_DeleteHandler">
</cc1:GenericDataSource>
Setup the "DataSourceID" property for the data bound control
<asp:GridView ID="GridView1" runat="server" DataSourceID="GenericDataSource1" AllowSorting="True" AllowPaging="true" DataKeyNames="TaskID" PageSize="4">
...
<asp:GridView>
Implement the Event Handlers
The following examples may be found in the supporting SampleWeb website. Check the website.
{
...
protected void GenericDataSource1_SelectHandler(object sender, GenericDataSourceControl.SelectDataEventArgs e)
{
//Retrieve the result for the SELECT
var theResult = ...
//Just setup the DataSource; in this case the GenericDataSource will perform Auto Sort and Auto Paging
e.SetResult ( theResult );
//to setup an already sorted and paged data, just use the ... e.SetPagedResult (thePageResult, totalRowCount);
}
protected void GenericDataSource1_InsertHandler(object sender, GenericDataSourceControl.InsertDataEventArgs e)
{
//create the new Entity object
var newItem = new T()
{
ID = Guid.NewGuid(),
....
};
//Fill the new created object with the Insert input parameters
e.SetInsert(newItem);
//Add the new Entity and submit the changes back to the database
...
}
protected void GenericDataSource1_UpdateHandler(object sender, GenericDataSourceControl.UpdateDataEventArgs e)
{
//Get the ID Entity key value; this value must be set on the GridView.DataKeyNames
var id = (Guid)e.Keys["ID"];
//Get the Entity object from the database
var item = ...
//Just setup the Task with the updated values from the user input
e.SetUpdate(item);
//or just retrieve the updated entity:
var updated = e.GetUpdate<T>();
//submit the change back to the database:
...
}
void GenericDataSource1_DeleteHandler(object sender, GenericDataSourceControl.DeleteDataEventArgs e)
{
//Get the ID key; this value must be set on the GridView.DataKeyNames
var id = (Guid)e.Keys["ID"];
//retrieve the entity by Key and delete it, or just call a Delete method with the entity Key.
...
}
...
}
That's it!