Tips & Tricks: Details View and Read-only Fields
One of the flexible and new features came with ASP.NET 2.0 was DetailsView control. This data bound control is used to display the values of a single record from a data source in an HTML table, where each table row represents a field of the record. The DetailsView control allows you to edit, delete, and insert records. In this post I will explain an issue related with Read-only data fields.
We will bound a DetailsView control to a SqlDataSource for simplicity reason you can use any data source control ... I used PetShop sample database for this example. After configuring the petShopSqlDataSource and enable update, insert and delete we set the DetailsView DataSourceId to our petShopSqlDataSource Id and so the DetailsView now have 3 fields bound to Category table.
What we need here is simple modification. I will edit the DetailsView filed and make the Name filed a read only filed by setting the Read-only property to true. And I already made this column does not accept null values in Category table.
What will happen here is when we try to update any record in the details view our application will throw this exception:
"Cannot insert the value NULL into column 'Name', table 'Petshop.dbo.Category'; column does not allow nulls. UPDATE fails.The statement has been terminated" as the message states the Name filed value seems to be passed as null to the data source although it was appeared in the DetailsView before.
To clarify this take a look into what's happen on the ItemUpdating event, if we checked the e.NewValues.Keys collection before we set the Name filed as read-only filed we will find that this collection contains two Items: Descn,Name after we set Name as read-only filed this collection will conation the Descn filed only as the below figure shows.
The DetailsView will not pass the read-only fields to the underlying data source and this is not an issue DetailsView designed like this. Take a look to HandleUpdate method in the DetailsView control using reflector and you will find it does not include Read-only fields when extracting values from fields.
Okay, we are done here so our tip is: if you set some fields as Read-only make sure you handle this case by using appropriate update statement, setting values pragmatically ... e.g.
Hope this helps
Huthaifa