[SalesForce] Display lists of strings as columns on VF page

So if I have lets say three string lists, how can I have each string appear as a column in a table on a VF page? Is it possible to have a PageBlockTable or would I have to build it another way?

List<String> firstName = new list<String> { 'John' , 'Amy' , 'Andrew'};
List<String> lastName = new list<String> { 'Smith' , 'Williams' , 'Jones'};
List<String> cityName = new list<String> { 'New York' , 'LA' , 'Miami'};

Best Answer

You can do this if you have a helper variable to access the indices. This example presumes that all lists are to be of equal length:

public class DemoController {
    public string[] firstName { get; set; }
    public string[] lastName { get; set; }
    public string[] cityName { get; set; }
    public Integer[] indexes { get; set; }
    public DemoController() {
        firstName = new string[] { 'John' , 'Amy' , 'Andrew'};
        lastName = new string[] { 'Smith' , 'Williams' , 'Jones'};
        cityName = new string[] { 'New York' , 'LA' , 'Miami'};
        indexes = new Integer[] { 0, 1, 2 };
    }
}

<apex:page controller="DemoController">
    <apex:pageBlock>
        <apex:pageBlockTable value="{!indexes}" var="index">
            <apex:column headerValue="First Name" value="{!firstName[index]}" />
            <apex:column headerValue="Last Name" value="{!lastName[index]}" />
            <apex:column headerValue="City" value="{!cityName[index]}" />
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

There are other ways to arrange this behavior, such as with CSS or potentially messing around with an apex:variable, but this technique is the one I generally regard as the safest method, even if it does use a bit more view state.