GridView with Edit Form (Template)
4.33/5 (3 votes)
Comfort editing of a GridView row.
Introduction
When I got my new job, I found out that developers there were still thinking in .NET 1.1, so they used old methods or directly edited HTML in Render methods. One of the controls made in this terrible way was a GridView that used an edit form instead of a classic edit row, and I wanted to make it the new (and I hope, also the right) way.
Background
Let's start designing:
- Get an
ITemplate(bindable) of the edit form - Insert the template into the row instead of default cells with inputs
- Extract the values on postback and use them to update the data source
Points of interest
The control itself is not complicated, so I will not describe all the code, I'll mention only the interesting parts.
- I needed a bindable template that can extract the entered values back, so I used the
IBindableTemplateand used it as the property. - And, the second thing is extracting the values:
[PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(GridViewRow),
System.ComponentModel.BindingDirection.TwoWay)]
public IBindableTemplate EditItemTemplate
{
set { _EditItemTemplate = value; }
get { return _EditItemTemplate; }
}
The interesting thing about this snippet is the attribute. Ordinary ITemplates provide only one way, so we can not extract the inserted values back, that's why I used the IBindableTemplate and declared two way binding direction in the attribute.
protected override void ExtractRowValues(
System.Collections.Specialized.IOrderedDictionary fieldValues,
GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
{
if (_EnableTemplateEditing)
{
// Not working
// fieldValues = _EditItemTemplate.ExtractValues(row.Cells[0]);
// Working
IOrderedDictionary dict = _EditItemTemplate.ExtractValues(row.Cells[0]);
foreach (string s in dict.Keys)
fieldValues.Add(s, dict[s]);
}
else
base.ExtractRowValues(fieldValues, row, includeReadOnlyFields,
includePrimaryKey);
}
The strange thing is that you can not assign the IOrderedDictionary you get from the template to the fieldValues object even if fieldValues is empty. You have to add the values key by key, as shown.
To enable template editing, don't forget to set the EnableTemplateEditing property to true.
History
- 2/9/2008 - First version.
- 2/12/2008 - Download added.
