Real World Example
For this example I will be using a common scenario developers encounter with
the DataGrid. The DataGrid gives us some powerful pre-built column objects,
including command columns which allow the user to press buttons (or links)
to select, edit, or delete items in the grid. Imagine you are writing a web
form which uses a DataGrid having a "Delete" column, and you want
to make the user confirm the deletion before actually deleting the item.
This is accomplished by using some client-side javascript to invoke the confirm
function in the onclick handler:
<... onclick="return confirm('Are you sure?');" >
The way that you attach this code to the Delete button is to add to the item's
Attributes collection when the item is created:
Control.Attributes.Add("onclick", "return
confirm('Are you sure?')");
You will typically find code like this in the Page class which is handling
the OnItemCreated event of the grid. It usually goes something like this:
private void InitializeComponent()
{
this.grid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
// ...(other handlers)...
}
private void OnItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs
e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Button btn = e.Item.FindControl("delbutton");
btn.Attributes.Add("onclick", "return confirm('Are you sure?')");
}
}
I find this approach to be flawed for two reasons:
- Encapsulation is being violated. Why is it the job for the Page object
to fiddle around with the internal attributes of the datagrid? It would
be ideal if the page object could simply set a boolean property to enable
the
confirmation message box.
- If you want to have delete confirmations for all 5 grids in all 5 pages
of your application, you are going to have to repeat at least some of this
code 5 times in your page classes. You can try to work around this by sharing
some common code, but you still have to hook up an event handler for each grid
in each page's
InitializeComponent.