Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
215
Add new Column in javascript
posted

Anyone know how to add a new column using javascript? i found a method insertColumn(colObj). But how create the column object? any suggestion would be appreciated. Thanks

Parents
  • 70
    Suggested Answer
    posted

    I have a similiar requirement but, unfortuantly, I couldn't accept "no" as an answer as any other solution would have taken just as long and probably entailed more risk and money.  Therefore I created a couple of JavaScript functions (think of them as being equilvent to extension methods in C#).

            /// <summary>
            /// Removes all rows and columns from a grid, effectively reseting it to a completely new grid.  This is useful
            /// for then dynmically re-populating the grid.
            ///
            /// NOTE: THIS CODE IS TIGHTLY BOUND TO THE INFRAGISTICS LIBRARY.  CHANGES TO THE INFRAGISTICS LIBRARY COULD RENDER
            /// THIS CODE INVALID.
            ///
            /// TODO: TEST THIS CODE WHEN UPGRADES ARE MADE TO THE INFRAGISTICS LIBRARY.
            ///
            /// </summary>
            /// <example>igtbl_resetGrid('<%= TestGrid.ID %>');</example>
            /// <param name="gridClientID">The ClientID of the Infragistics grid to be reset</param>
            function igtbl_resetGrid(gridClientID)
            {
                var grid = igtbl_getGridById(gridClientID);
               
                if(grid != null)
                {
                    var gridHasRowSelectors = (grid.RowSelectors == 1);                 // Determine if the first column is the row selector column
                    var endElementPos = (gridHasRowSelectors == true ? 1 : 0);          // If yes then we want to leave this
                   
                    /* Remove all the rows first */
                    var rowCount = grid.Rows.length;
                    var rowCounter = rowCount - 1;
                   
                    for(rowCounter; rowCounter >= 0; rowCounter--)
                    {
                        try
                        {
                            grid.Rows.remove(rowCounter, false);                            // false signifies that we do not want to fire events
                        }
                        catch(e)
                        {
                            // An error is thrown using FireFox, but the row still gets removed.  Hence
                            // we just need to catch it but do nothing with it.
                        }
                    }
                   
                    /* Now remove the column headings by manipulating the DOM... */
                    var tableDiv = grid.getDivElement();
                    var table = tableDiv.childNodes[0];                                 // Move to the TABLE element which represents the actual table
                    var childElementCounter = 0;
                    var childElements = table.childNodes.length;
                   
                    var removeTableElementsDelegate = function(parentElement)
                        {
                            // Iterate over each child element and remove it from the DOM.
                            var elementCounter = parentElement.childNodes.length - 1;
                           
                            for(elementCounter; elementCounter >= endElementPos; elementCounter --)
                            {
                                parentElement.removeChild(parentElement.childNodes[elementCounter]);
                            }
                        };
                   
                    for(childElementCounter; childElementCounter < childElements; childElementCounter ++)
                    {
                        switch(table.childNodes[childElementCounter].tagName)
                        {
                            case "COLGROUP":
                                // Remove the COL elements from the DOM
                                var colGroup = table.childNodes[childElementCounter];
                                removeTableElementsDelegate(colGroup);
                                break;
                            case "THEAD":
                                // Remove the TH elements from the DOM
                                var tr = table.childNodes[childElementCounter].childNodes[0];
                                removeTableElementsDelegate(tr);
                                break;
                            default:
                                break;
                        }
                    }
                   
                    // Finally remove the columns from the Infragistics CSOM
                    grid.Bands[0].Columns = [];
                }
                else
                {
                    // TODO: Handle this unexpected situation...
                }
            }

    The above function resets a grid i.e. removes all rows and columns.

            /// <summary>
            /// Adds a new column to band 0 of an Infragistics grid using JavaScript.  This presents the opportunity of populating
            /// the grid without having to do a postback (i.e. the data could be obtained using much lighter-weight web services).
            ///
            /// NOTE: THIS CODE IS TIGHTLY BOUND TO THE INFRAGISTICS LIBRARY.  CHANGES TO THE INFRAGISTICS LIBRARY COULD RENDER
            /// THIS CODE INVALID.
            ///
            /// TODO: TEST THIS CODE WHEN UPGRADES ARE MADE TO THE INFRAGISTICS LIBRARY.
            ///
            /// </summary>
            /// <example>igtbl_addColumnToGrid('<%= TestGrid.ID %>', 0, 'Col1', 'Column 1', '150px', 'calculatorGridSelectedRowStyle', 'calculatorGridDisabledCellStyle', 'ig_b3617fe8_r1 ig_b3617fe8_r4 calculatorGridRowStyle');</example>
            /// <param name="gridClientID">The ClientID of the Infragistics grid</param>
            /// <param name="columnKey">The unqiue key of the column to be added</param>
            /// <param name="columnName">The caption of the column to be added</param>
            /// <param name="columnType">The type of the column as defined by Infragistics.  0 - NotSet, 3 - CheckBox, 5 - DropDownList, 7 - Button.  Simple textual values should be set to 0.</param>
            /// <param name="width">The width of the new column</param>
            /// <param name="selectedRowStyle">The selected row CSS class name</param>
            /// <param name="cellStyle">The cell CSS class name</param>
            /// <param name="rowStyle">The row CSS class name</param>
            function igtbl_addColumnToGrid(gridClientID, columnKey, columnName, columnType, width, selectedRowStyle, cellStyle, rowStyle)
            {
                var gridInputElement = $get(gridClientID);                          // Get the hidden Input element that surrounds the Grid object
               
                if(gridInputElement != null)
                {
                    var gridInternalID = gridInputElement.attributes['name'].value;       // Get the Infragistics internal ID of the grid so that we can successfully add new columns
                    var grid = igtbl_getGridById(gridClientID);                     // Get the Grid object from the Infragistics CSOM
                    var tableDiv = grid.getDivElement();
                    var band = grid.Bands[0];
                    var indexPosition = band.Columns.length;
                   
                    // Create the column initiaization array which is used by the Infragistics CSOM to instantiate new Column object instances
                    var columnInitializationArray = [columnKey,columnName,8,0,false,1,0,2,0,0,0,0,false,"",false,0,"","",selectedRowStyle,selectedRowStyle,columnType,"",[],"","","",0,[],cellStyle,"",width,true,false,false,rowStyle,"width:100%;height:100%;",false,rowStyle,0,"","","",false,"","","","",false,[],2,1,1,true,0,3,1,0,true,width];
                   
                    var table = tableDiv.childNodes[0];
                    var childElements = table.childNodes.length;
                    var childElementCounter = 0;
                   
                    // Step 1. Manipulate the DOM to add the new column
                    for(childElementCounter; childElementCounter < childElements; childElementCounter ++)
                    {
                        switch(table.childNodes[childElementCounter].tagName)
                        {
                            case "COLGROUP":
                                // Add a new COL element
                                var colGroup = table.childNodes[childElementCounter];
                                var col = document.createElement('col');
                                col.setAttribute('width', width);
                                colGroup.appendChild(col);
                                break;
                            case "THEAD":
                                // Add a new TH element
                                var tr = table.childNodes[childElementCounter].childNodes[0];
                               
                                var columnCaption = document.createElement('NOBR');
                                columnCaption.innerHTML = columnName;
                               
                                var column = document.createElement('TH');
                                column.setAttribute('id', gridInternalID + '_c_0_' + indexPosition);
                                column.setAttribute('columnNo', indexPosition);
                                column.setAttribute('height', '');
                                column.setAttribute('class', rowStyle);
                                column.appendChild(columnCaption);
                               
                                tr.appendChild(column);
                                break;
                            default:
                                break;
                        }
                    }
                   
                    // Step 2. Add the new column to the Infragistics CSOM so that it's available for later manipulation
                    var newColumn = new igtbl_Column(null, band, indexPosition, -1, columnInitializationArray);
                   
                    Array.add(band.Columns, newColumn);
                    band.VisibleColumnsCount++;
                   
                    band.Columns[indexPosition].setWidth(300);
                }
                else
                {
                    // TODO: Handle this unexpected situation...
                }
            }

    The above function adds columns to grids.

    The following code shows how the above can be used.

            function doAddTest()
            {
                igtbl_addColumnToGrid('<%= TestGrid.ClientID %>', 'Col2', 'Life', 0, '300px', 'calculatorGridSelectedRowStyle', 'calculatorGridDisabledCellStyle', 'ig_b3617fe8_r1 ig_b3617fe8_r4 calculatorGridRowStyle');
                igtbl_addColumnToGrid('<%= TestGrid.ClientID %>', 'Col3', 'ADB', 0, '300px', 'calculatorGridSelectedRowStyle', 'calculatorGridDisabledCellStyle', 'ig_b3617fe8_r1 ig_b3617fe8_r4 calculatorGridRowStyle');
                igtbl_addColumnToGrid('<%= TestGrid.ClientID %>', 'Col4', ' ', 3, '300px', 'calculatorGridSelectedRowStyle', 'calculatorGridDisabledCellStyle', 'ig_b3617fe8_r1 ig_b3617fe8_r4 calculatorGridRowStyle');
               
                var grid = igtbl_getGridById('<%= TestGrid.ClientID %>');
                grid.Bands[0].Columns[1].setAllowUpdate(1);
                grid.Bands[0].Columns[2].setAllowUpdate(1);
            }
           
            function doResetTest()
            {
                igtbl_resetGrid('<%= TestGrid.ClientID %>');
            }
           
            function doAddRowTest()
            {
                var grid = igtbl_getGridById('<%= TestGrid.ClientID %>');
               
                if(grid != null)
                {
                    var row = igtbl_addNew(grid.Id, 0, false, false);
                    var columns = grid.Bands[0].Columns.length;
                    var columnCounter = 0;
                   
                    for(columnCounter; columnCounter < columns; columnCounter ++)
                    {
                        var cell = row.getCell(columnCounter);
                        var column = grid.Bands[0].Columns[columnCounter];
                   
                        if(column.ColumnType == 0)
                        {
                            // cell.setValue(columnCounter + " <b>Testing</b>");
                            cell.setValue(columnCounter);
                            cell.getElement().innerHTML = columnCounter + " <b>Testing</b>"
                        }
                    }
                }
            }
           
            function getRowTest()
            {
                var grid = igtbl_getGridById('<%= TestGrid.ClientID %>');
               
                if(grid != null)
                {
                    var rows = grid.Rows.length;
                    var rowCounter = 0;
                    var rowData = "";
                   
                    for(rowCounter; rowCounter < rows; rowCounter++)
                    {
                        rowData += "\nrow " + rowCounter + "..."
                       
                        var row = grid.Rows.getRow(rowCounter);
                        var cells = row.getCellElements().length;
                        var cellCounter = 0;
                       
                        for(cellCounter; cellCounter <cells; cellCounter ++)
                        {
                            rowData += "," + row.getCell(cellCounter).getValue();
                        }
                    }
                   
                    alert(rowData);
                }
            }

     

    The function doAddTest() demostrates that once the columns have been added in this round-about-way, they can still can manipulated as if they had been added in the conventional manner by the Infragistics CSOM.

    Hope this helps someone else!

    NOTE: I have only tested this with the latest versions of IE (8) and Firefox (3.6.2) but it works perfectly in both.

     

Reply Children
No Data