Thursday, 2 June 2011

Inner Wrapper Class in Apex Class


I have seen a lot of questions regarding inner class in a apex class in developer community and issues that can be solved by use of inner class. So here I would like to show a problem which can also be solved by inner class.

Syntax of inner class :

public class myOuterClass {
   // Additional myOuterClass code here  
   class myInnerClass {
     // myInnerClass code here  

Problem :

When i click on add button i need to display one more textbox

Visual Force Page :
<apex:page controller="addTextrBox">
       <apex:commandButton Value="Add Text Box" action="{!addTextBox}"/>
       <apex:repeat value="{!listvalueOfTextBox}" var="item" rendered="{!IF(listvalueOfTextBox.size > 0 , true , false)}" >
           <apex:outPutLabel value="{!item.textBoxLabel}">
           <apex:inputText value="{!item.textBoxValue}"/>

Apex Controller Class

public class addTextrBox 

    public List<textBoxClass> listValueOfTextBox
    public addTextrBox ()
            listvalueOfTextBox = new List<textBoxClass>();
    public PageReference addTextBox() 
                    listvalueOfTextBox.add(new textBoxClass('TextBox' + (listvalueOfTextBox.size() +  1)));
            catch(Exception e)
            return ApexPages.currentPage();

     public class textBoxClass
             public string textBoxLabel{get;set;}
             public string textBoxValue{get;set;}
             public textBoxClass(String textBoxLabel)
                     this.textBoxLabel = textBoxLabel;

Here textBoxClass is the inner class

In above problem we used iner class now any new text box is binded with a new item in the list listvalueOfTextBox which is of type textBoxClass.

inner class acan be intancitiated like this
outerClass.innerclass instanceOfinnerClass = new outerClass.innerclass();

in above case it will be like
addTextrBox.textBoxClass instaceOftextBoxClass = new addTextrBox.textBoxClass('Test text Box');



  1. Your welcome Narasimha, happy to know it helped you.

  2. Hi Shashi,
    Here in this sample i could only add the textboxes in row wise.
    Can u show me how can i add textboxes in both row and col wise.(here i will enter rownumber and colnumber values in text fields). By clicking a button i need to add textboxes in both rows and cols.

  3. Hi Narasimha
    How to write clear() option in apex class
    please send

  4. Hi Shashikant. It is great to see some explanations for inner classes. I'm wondering if you have an even more basic, simple explanation or have seen one online? I'm just starting with code and I'm trying to wrap my head around when I would use an inner class instead of another class that is referenced. Thanks for any help.