DHTMLX Docs & Samples Explorer

Index
dhtmlxgrid

## Step 6 - Add/Remove Rows in Grid

Here I would say some words about adding rows into grid and removing rows with the help of Script API (set of methods which help you manage grid through JavaScript). First of all we'll need to add two buttons to the page: “Add Row” and “Remove Row”. Do this by adding the following HTML code to the body of your page right after grid:

        <button onclick="addRow()">Add Row</button>   <button onclick="removeRow()">Remove Row</button>

Most important things here are two function calls, which occure when you click the first or the second button: addRow() and removeRow() respectively. Let's add these function to the script block where you already have doInitGrid() function. The code you need to add is the following:

        function addRow(){
            var newId = (new Date()).valueOf()
            mygrid.addRow(newId,"",mygrid.getRowsNum())
            mygrid.selectRow(mygrid.getRowIndex(newId),false,false,true);
        }
        function removeRow(){
            var selId = mygrid.getSelectedId()
            mygrid.deleteRow(selId);
        }

Some comments about addRow() function code (line by line):

- Creates a unique value (number of millisecond since 1970) to use as row identifier;
- Adds a row with a new Id, empty values and put it after the last row in grid;
- Selects the newly created row (by index), without calling for On-Select event handler, without preserving previously selected rows and with setting focus on the selected row (will scroll to it if vertical scroller exists).

Some comments about removeRow() function code (line by line):

- Gets Id of the selected row;
- Deletes the row with the specified Id.