Adding Custom Functionality to ASP.NET DataViews
The ASP.NET DataViews, when connected to a DataSource, generate all the buttons a user needs to edit, update and delete the data that the DataView displays (assuming that you enable edits, updates and deletes).
But what if you want to add some additional functionality to the form? If, for instance, you want the user to be able to click a button to run a credit check on the currently displayed customer? Or, for some change that requires coordinating changes to several values, you want to give the user the ability to implement the update with a single button click? Or, by clicking a button, delete not the currently displayed record but some other, related set of records (i.e. "Delete all orders for this customer")? You can put that code where it belongs -- associated with the DataView -- rather than scattered through several Click events by using the FormView's ItemCommand method.
All you have to do is drop a Button of your own onto the form and set the Button's CommandName property to some string. When the user clicks on any Button on the DataView, the DataView fires its ItemCommand event. The e parameter to that event has a property called CommandName that's automatically set to whatever was in the CommandName property of the button that triggered the event. You can use that value to check to see which Button was clicked and execute your code. Typical ItemCommand code will look like this:
Select Case e.CommandArgument
'CommandArguments for other buttons
This event has two other properties useful in this scenario. The CommandArgument property contains the value of the CommandArgument property on the Button the user clicked. You can store data in the CommandArgument that will be passed to the ItemCommand event when the Button is clicked. Less useful is the CommandSource, which points at the Button that fired the event (the sender parameter passed to the event points to the DataView).
And, because the ItemCommand event fires for every Button on the page and fires before any of the events triggered by that button, the ItemCommand event lets you preview all other Button clicks on the page. This allows you to use the ItemCommand event as a central point-of-control for every Button on the DataView.
Posted by Peter Vogel on 10/24/2011 at 1:48 PM