lunedì 10 novembre 2008

How to derive a web control from another one

I'm developing an project containing a repeater; it is filled with a datatable and every item of the repeater contains some web controls, including a button. In response to the click on one of the buttons I have to delete a record in the table referenced by an unique ID. Many possibilities exist, usually a common solution is to use the property "CommandArgument", but because I like elegance (and using a string property to store an integer isn't elegant!), to explore new solutions and, finally, because I want to lose my VB roots and to enter the wonderful world of the C# OO programming I tried the way of creating a new web control, similar to a button, but with a new property, RecordId, useful to store an integer: the natural way is to derive the new control from a button.

The steps to accomplish this easy job are:

- Start Visual C# Express 2008 (or equivalent)

- Create a new Class Library project

- Add System.Web to references

- Rename the class with a significant name (for example ButtonExt)

- Define the new control in the namespace System.Web.UI.WebControls

- Derive the class from System.Web.UI.WebControls.Button

- Add the RecordId property

- Override LoadViewState and SaveViewState for viewstate managing

- Compile and obtain the DLL of the new control

And if you want to use it:

- Create a new project

- Add the DLL of the control to references

- Drag the DLL of the control to the General Section of the Toolbox

- Drag the control to the form and use it!

My two cents

Download source

Download example

Nessun commento: