# Creating Data Grids with CFGRID

The CFGRID tag allows you to build CFFORM grid controls. A grid control resembles a spreadsheet table and can contain data populated from a CFQUERY or from other sources of data. As with other CFFORM tags, CFGRID offers a wide range of data formatting options as well as the option of validating user selections with a JavaScript validation script.

You can also do the following with CFGRID:

- Sort data in the grid alphanumerically
- Update , insert and delete data
- Embed images in the grid

When users select grid data and submit the form, ColdFusion passes the selection information as form variables to the application page specified in the CFFORM ACTION attribute.

Just as the CFTREE tag uses CFTREEITEM, CFGRID uses the CFGRIDCOLUMN tag. You define a wide range of row and column formatting options, as well as a query name, selection options, and so on. You use the CFGRIDCOLUMN tag to define individual columns in the grid.

## Populating a grid from a query

| To populate a grid from a query:

1. Open a new file named `grid1.cfm` in Studio.
2. Edit the file so that it appears as follows:

       <CFQUERY NAME="empdata" DATASOURCE="CompanyInfo">
           SELECT * FROM Employees
       </CFQUERY>

       <CFFORM NAME="Form1" ACTION="submit.cfm" METHOD="Post">

           <CFGRID NAME="employee_grid" QUERY="empdata"
                   SELECTMODE="single">
               <CFGRIDCOLUMN NAME="Employee_ID">
               <CFGRIDCOLUMN NAME="LastName">
               <CFGRIDCOLUMN NAME="Department_ID">
           </CFGRID>

       <BR><INPUT TYPE="Submit" VALUE="Submit">
       </CFFORM>

       Note
       Use the CFGRIDCOLUMN DISPLAY="No" attribute to hide columns
       you want to retrieve from a data source but not expose to an end
       user.

3. Save the file and view it in your browser.

### Code Review

Code | Description
--- | ---
    <CFGRID NAME="employee_grid"
    QUERY="empdata"
| Create a grid named "employee_grid" and popluate it with the results of the query "empdata"
    SELECTMODE="single">
| Allow the user to select only one cell.
    <CFGRIDCOLUMN NAME="Employee_ID">
| Put the contents of the Employee_ID column in the query results in the first column of the grid
    <CFGRIDCOLUMN NAME="LastName">
| Put the contents of the LastName column in the query results in the second column of the grid
    <CFGRIDCOLUMN NAME="Department_ID">
| Put the contents of the Department_ID column in the query results in the third column of the grid

Note | If you specify a CFGRID tag with a QUERY attribute defined and no corresponding CFGRIDITEM attributes the default grid that is created contains all the columns in the query.