5

I'm working with Handsontable to create a web grid that can copy / paste between web and excel, I tried with code below and it works fine:

  var first = true;
  var exampleGrid = $("#exampleGrid");
  exampleGrid.handsontable({
      rowHeaders: true,
      colHeaders: true,
      stretchH: 'all',
      minSpareCols: 0,
      minSpareRows: 0,
      height: 600,
      columns: [
      { data: "Id", title: "ID", type: "text" }, //'text' is default, you don't actually have to declare it
      { data: "Name", title: "Name", type: "text" },
      { data: "DisplayColor",
      title: "Display Color",
      type: 'autocomplete',
      source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"]
      },
      { data: "Description", title: "Description", type: 'text' },
      { data: "IsDeleted", title: "Is Deleted", type: 'checkbox' }
      ],
      colWidths: [400, 100, 60, 100, 50, 40, 40, 60], //can also be a number or a function
      contextMenu: false,
  });

Now I need create web grid with dynamic columns, I tried replace the column list with function below, but it does not works:

    columns:
        function () {
            var cols = [];
            for (var i = 0; i < 1; i++) {
                var col = new Object();

                col.data = "Name";
                col.title = "Name" + i.toString();
                col.type = "text";
                cols[i] = col;
            }
            return cols;
        },

Is it possible to create dynamic columns in Handsontable grid? and how to do it?

I'm a JavaScript beginner, so please tell me if there is any error I made, thanks!

xinfli
  • 211
  • 1
  • 2
  • 6

1 Answers1

16

Resolved this problem by myself, function can not be used in column definition directly, but variable is allowed, so code below works:

var dynamicColumns = [];
for (var i = 0; i < 366; i++) {
    var col = new Object();
    col.data = "Name";
    col.title = "Name " + i.toString();
    col.type = "text";
    dynamicColumns.push(col);
}

skillGrid.handsontable({
    // ...
    columns: dynamicColumns,
    // ...
xinfli
  • 211
  • 1
  • 2
  • 6
  • @GôTô, as the owner of the question you are the one that has to chose the right answer (in this case there is only one and it is the correct one). Not the other way around. Otherwise "everyone" could select their answer as the one that is correct :). – Helmut Granda Jun 23 '16 at 05:26
  • @HelmutGranda This answer is provided by the person who asked the question........... – GôTô Jun 23 '16 at 06:50