[SalesForce] rendering the table data through apex code

I am trying to fetch the custom object data into page block table with below code. I am getting the table as expected but my need is not to get the data when page is loaded and should come true only on button click.

I gone through the rendered attribute in page block table tag and need to be false initially and should become on button click. So here, how to set the rendered attribute to true from apex code.

besides, Is it right approach to do my requirement or can we get the data into list only after button click.

VF page:

<apex:page controller="deptWrapper">
<apex:form >
  <apex:pageBlock title="Department List">
          <apex:commandButton action="{!show}" value="Show" id="cb"/>
          <apex:pageblocktable rendered="false" value="{!Departments}" var="dept_ref">

             <apex:column value="{!dept_ref.Subject__c}"/>
             <apex:column value="{!dept_ref.Syllabus__c}"/>
             <apex:column value="{!dept_ref.Employees__c}" headervalue="Emp count"/>
             <apex:column headervalue="Name" value="{!dept_ref.Name}"/>

          </apex:pageblocktable>
  </apex:pageBlock>
  </apex:form>
</apex:page>

Apex:

public class deptWrapper {

    public void show() {
        return null;
    }

    public ApexPages.StandardSetController dept_list {
        get {
            if(dept_list == null) {
                dept_list = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT Name,Subject__c, Syllabus__c,Employees__c FROM Department__c]));
            }
            return dept_list;
        }
        set;
    }
     public List<Department__c> getDepartments() {
        return (List<Department__c>) dept_list.getRecords();
    }
}

Best Answer

I would just use a controller property to control the visibility. You also need to use the rerender property for the commandButton. Something like this

VF Page

<apex:commandButton action="{!show}" value="Show" id="cb" rerender="myTable"/>

<apex:pageblocktable rendered="{!showTable}" value="{!Departments}" var="dept_ref" id="myTable">

     <apex:column value="{!dept_ref.Subject__c}"/>
     <apex:column value="{!dept_ref.Syllabus__c}"/>
     <apex:column value="{!dept_ref.Employees__c}" headervalue="Emp count"/>
     <apex:column headervalue="Name" value="{!dept_ref.Name}"/>

</apex:pageblocktable>

APEX

public class myController {

    public boolean showTable      {get;set;}

    public myController() {
         showTable = false;
    }

    public void show() {
         showTable = true;
    } 
}