I am working on building a DataGrid that has two states: the standard
"read-only" state, where all the columns and rows of the DataGrid are
shown as text; and a fully editable state, where all rows are treated as
if they were the EditItemIndex row.
Now, I created a class derived from DataGrid to accomplish this. I
overrode the CreateItem() method of the DataGrid like so:
protected override DataGridItem CreateItem(int itemIndex, int
dataSourceIndex, ListItemType itemType)
{
if (itemType == ListItemType.Item || itemType ==
ListItemType.AlternatingItem)
{
if (_editable)
return new DataGridItem(itemIndex, dataSourceIndex,
ListItemType.EditItem);
}
return new DataGridItem(itemIndex, dataSourceIndex, itemType);
}
(Here, _editable) is a private variable that can be toggled, indicating
whether or not the DataGrid should be displayed in edit mode...) As you
can see, if _editable is true and we are dealing with an Item or
AlternatingItem then the DataGridItem is created as an editable item. This
all works great when you set _editable to True. However, for some reason
the ViewState for the DataGrid's columns are not being saved across
postbacks. That is, the following sequence of events produces a "weird"
result: 1.) I have my Editable Grid in read-only mode first 2.) I
click on a button which causes a postback and sets the _editable flag and
rebinds the data; now, all of the rows are in editable mode. 3.) I
click on a button that does nothing, just causes a postback, and the
DataGrid's editable cells now are blank - no text, no textboxes... What
gives? I would have thought all of this was taken care of for me behind
the scenes since I am, after all, only make a tiny change, namely making
each DataGridItem's ItemType EditItem. BoundCOlumns that are marked
ReadOnly (i..e, ReadOnly="True") do not disappear, only those columns that
are forcibly made into editable columns. Another twist: if I set the
EditItemIndex to, say 1, all editable columns SAVE the columns for Row #2
disappear... For example, if I set EditItemIndex to 1, upon the first
visit I see this screenshot. Then, if I click on the button that sets
_editable to True, I see this screenshot. Finally, when I click on the
"Cancel without saving Changes" button I see this screenshot. Note in the
final screenshot that all of the columns have disappeared save the first
one (which is a BoundColumn with ReadOnly="True" and the colunns for Row
#2...) I am hoping you can quickly see what the problem is. I think it's
pretty clear it's a ViewState problem, I've been digging through the
DataGrid/DataGridColumn/DataGridColumnCollection methods the better half
of the day, but am stuck. I don't see why the editing interface wouldn't
get saved automatically by the DataGridColumnCollection's SaveViewState()
call. Any ideas? Thanks!
--
Scott Mitchell
mitchell (AT) 4guysfromrolla (DOT) com
http://www.4GuysFromRolla.com http://www.ASPFAQs.com http://www.ASPMessageboard.com
* When you think ASP, think 4GuysFromRolla.com!