As discussed in detail in Chapter 9 of ASP.NET Data Web Controls Kick Start, the DataGrid provides the ability to edit the data in its rows one row at a time. This built-in editing support is relatively easy to implement and can greatly enhance the funtionality of a Web page.
Unfortunately, when using the DataGrid's built-in editing features, there is no property that can be set that indicates that a certain row, or set of rows, should not be editable. For example, consider the case where you are displaying a set of data to a user, but, based on the user, you only want to make certain rows editable. To provide such functionality we have to roll up our sleeves and do a bit of work ourselves.
The first step is to create an event handler for the DataGrid's ItemDataBound event. Then, in this event handler we
want to check to see if we are dealing with an item in the DataGrid (i.e., not the header or footer row). If we are dealing with an
item (that is, a DataGridItem whose ItemType is either ListItem.Item or ListItem.AlternatingItem),
then we can perform our security check. This likely would involve checking some field in the DataGridItem's DataItem
property. Finally, if we need to disable editing for this particular row, we simply set the Visibility property of the
appropriate DataGrid column's first control to False.
The DataGrid column's whose first control's Visible property is set to False is the EditCommandColumn column. The first (and only)
control in the EditCommandColumn for a row that's not being currently edited is the "Edit" LinkButton or Button Web control. By setting this
control's Visible property to False, the "Edit" button is not rendered, thereby restricting the user from editing the row.
(Note that this is not fool-proof, as a skilled user could create a dummy Web page with identical HTML and then add in the needed HTML by hand.
To prevent this, it would be wise to check in the EditCommand event handler that the user has permission to edit the row selected...)
The code to complete this, in both VB.NET and C#, can be seen below. There's also a live demo worth checking out.
|
|
| VB |
|
|
| C# |
Be sure to check out the live demo!
Home | FAQs | Articles | About | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.