Flex: Delete item from collection bound to datagrid and update the grid selected index
I have a datagrid with an xmlListCollection bound to it:
<mx:DataGrid id="dgCompetente" includeIn="Competente" x="10" y="66" width="547" height="468"
change="dgCompetente_changeHandler(event)" dataProvider="{colCompetente}"
editable="false">
<mx:columns>
<mx:DataGridColumn headerText="ID Competenţă" dataField="idCompetenta"/>
<mx:DataGridColumn headerText="Denumire Competenţă" dataField="denCompetenta"/>
<mx:DataGridColumn headerText="Competenţă Superioară" dataField="idCompSuperioara" labelFunction="labelFunctionCompetentaSuperioara"/>
</mx:columns>
</mx:DataGrid>
and a button to delete the currently selected item in the datagrid, which has this function assigne开发者_运维问答d to the click event:
<s:Button id="btnDeleteCompetenta" includeIn="Competente" x="813" y="65" label="Stergere" click="deleteCompetenta()"/>
private function deleteCompetenta():void
{
try {
var position:int = dgCompetente.selectedIndex;
if (position >= 0) {
colCompetente.removeItemAt(position);
dgCompetente.selectedIndex = position;
}
clearEdit(fieldsCompetente);
saveCompetente();
} catch (error:Error) {
errorHandler.defaultErrorHandler(error);
}
}
I want the selectedIndex to remain the same. So, if I delete item 2, the next in the list should be selected. The problem is that if I delete item 2, item 3 will be selected and I have no idea why.
Can someone tell me what I'm missing?
Thank you!
It doesn't work selectedIndex don't update with the good value also in updateCompleteHandler but with value-1 if force value+1, take value+2 and the selection escape from click, so it's exactly the same.
You're probably resetting the selectedIndex too early, before the DataGrid is updated, but it's hard to tell exactly since your code calls a bunch of functions. Try this
Add a "cached position" variable, like this:
protected var cachedPosition : int;
Then modify your deleteCompetenta method
private function deleteCompetenta():void
{
try {
cachedPosition = dgCompetente.selectedIndex;
if (position >= 0) {
colCompetente.removeItemAt(position);
// don't reset this here
// dgCompetente.selectedIndex = position;
}
clearEdit(fieldsCompetente);
saveCompetente();
} catch (error:Error) {
errorHandler.defaultErrorHandler(error);
}
}
Then add an updateCompleteHander to the DataGrid:
<mx:DataGrid id="dgCompetente" includeIn="Competente" x="10" y="66" width="547" height="468"
change="dgCompetente_changeHandler(event)" dataProvider="{colCompetente}"
editable="false" updateComplete="updateCompleteHandler(event)">
And reset the selectedIndex int he updateCompleteHandler:
protected function updateCompleteHandler(event:Event):void{
// reset here
dgCompetente.selectedIndex = cachedPosition;
}
Would that solve it?
精彩评论