+ Start a Discussion

Bug on Removing dynamic Textboxes




     I've created page whenever click on add button two textboxes would be create.

When click on remove button textboxes would be delete. But when i delete Index [1] the textbox will deleted and when i  try to delete Index[4] below error occuring.. Error occuring only on remove method


My code everything is correct except below bug


   System.ListException: List index out of bounds: 3

Error is in expression '{!remove}' in component <apex:page> in page shravan1:day5task3



public with sharing class textboxcls {

public PageReference save() {

List<Account> lst=new List<Account>();

for(wrapper w:lstwrap){
insert lst;

return null;

public Integer rowId{get;set;}

public PageReference remove() {


return null;

public PageReference add() {

lstwrap.add(new wrapper(lstwrap.size() ,new Account()));

// system.debug('****************************size*****************************'+lstwrap.size());

return null;

public List<wrapper> lstwrap {get; set;}

public class wrapper {

public Integer Index {get; set;}
public Account acc {get; set;}

public wrapper(Integer i, Account a){

Index =i;

public textboxcls(){

lstwrap=new list<wrapper>();
lstwrap.add(new wrapper(0,new Account()));











<apex:page controller="textboxcls" showHeader="true">
<apex:form >
<apex:actionFunction name="remove" action="{!remove}" reRender="out">
<apex:param value=" " assignTo="{!rowId}" name="p"/>

<apex:pageBlock >
<apex:outputPanel id="out">
<td>Account Name</td>
<apex:repeat value="{!lstwrap}" var="w">
<apex:inputText value="{!w.acc.name}"/>

<apex:inputText value="{!w.acc.phone}"/>
<apex:commandButton value="+" action="{!add}" reRender="out"/>
<apex:commandButton value="-" style="{!if(w.index == 0,'visibility:hidden','visibility:visible')}" onclick=" return remove('{!w.Index}')" reRender="out"/>

<apex:commandButton value="Save" action="{!save}"/>

ForceMantis (Amit Jain)ForceMantis (Amit Jain)

Hi Shravan


In Apex Collections are dynamic, which means when you add items to it these are added at last position, when you remove items items below it are shifted upwards.


I see you are removing based on index, which is fine, but you are not re-calculating index after deletion in your wrapper class.


Say you deleted item that had index = 1, and before this deletion your collection had 4 items. After deletion it will have 3 items so only 0, 1, 2 index position are valid. In your wrapper class it will have values 0, 2, 3 so certainly if you try to delete last item(3) it will give error and if you try to delete 2nd item will actually delete item on index 2 which is Item 3 on view. 


I hope this throws some light on what is happening behind the scene.