Print this page

Adding Columns Dynamically into PageBlockTable at run time

Knowledge Article Number 000229612

Sample code which adds the Columns dynamically to a PageBlockTable based on the Value you enter in a text box on Visualforce page.

Resolution User-added image

This example shows how the Fields can be added at runtime for Account's records dynamically.

There are three custom validation errors in this page:-

1) User can not select duplicate fields.
2) User can not enter wrong Field name.
3) User can not leave the text box blank If click on Add Field Button.

Please note that the below codes are just examples. You need to modify and test it to meet your needs.


<apex:page controller="Dynamic_Column_Controller">
<apex:form >
<apex:pageMessages id="ss"></apex:pageMessages>

<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockSectionItem >

<b>Field API Name</b> <apex:inputText id="input1" value="{!FieldName}" />


<apex:pageBlockTable id="table1" value="{!accs}" var="rec">

<apex:repeat value="{!SelectedFields}" var="FieldLable"> 
<apex:column value="{!rec[FieldLable]}"/> 

<apex:pageBlockButtons >
<apex:commandButton reRender="table1,ss" value="Add Fields" action="{!addFields}"/>


Public Class Dynamic_Column_Controller

public List<Account> accs {get;set;}
public List<String> SelectedFields {get; set;} 
public string FieldName {get;set;}
string query;
string fields = '';

public void addFields()

If (FieldName == '' )
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Please give a Field Name'));


fields = String.Join(SelectedFields, ', ');
fields = fields.RemoveEnd(',');
query = 'Select ' + fields + ' From Account Limit 10';

accs= Database.Query(query);
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Field : ' + FieldName + ' is added in below table'));

catch( Exception e )

If ( e.getmessage().contains('No such column') )
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Warning,'Field : ' + FieldName + ' is not avaialble on Account'));

If ( e.getmessage().contains('duplicate') )
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Field : ' + FieldName + ' is already selected '));



public Dynamic_Column_Controller()
SelectedFields = New List<String>();





promote demote