Add text boxes to DataGrid Columns programatically

I want to create a component for adding data to a data grid (similar to this tutorial). However, I need to add each text box programmatically, since the columns are dynamic.

I am using code that looks like this:

drp = DataRowPanel()
for i in range(num_columns):
    drp.add_component(TextBox(), column=i)
self.project_experiments_grid.add_component(drp)

And I get this result:

The text boxes are not constrained to the columns as I would like. Any ideas why?

Hello and welcome,

You may find the documentation on DataGrids helpful.

If you want TextBox components inside the DataRowPanel so that the columns are consistent with the DataGrid, you could try this approach.

grid=DataGrid()
self.add_component(grid)

# create some columns
grid.columns = [
  { "id": "A", "title": "Name", "data_key": "name" },
  { "id": "B", "title": "Address", "data_key": "address" },
  { "id": "C", "title": "Age", "data_key": "age" }
]

# create some rows of data
items = [
{'name': 'Alice', 'address': '1 Road Street', 'age': "10"},
{'name': 'Bob', 'address': '2 City Town',  'age': "20"}
]
  
# extracting the column IDs
col_ids=[x["id"] for x in grid.columns]
  
# programatically align data and columns using TexBoxes and DataRowPanels
for item in items:
  drp = DataRowPanel()
  for ID, data in zip(col_ids, item.values()):
    drp.add_component(TextBox(text=data), column=ID)
    
  grid.add_component(drp)

While this is totally doable, if each row contains the same set of elements, you may consider exploring RepeatingPanels and their use within DataGrids (see the docs above).

Lastly, I believe you are referring to DataGrid components rather than DataTables (Anvil’s built in database service). I’ve edited the title and post accordingly, but please feel free to correct it if I have misunderstood.

2 Likes

Hi @kobi.c.f,

By default, the ID of a Data Grid column is a random string, so you need to get the ID out of the Data Grid’s columns property. Your code will work if you change it to this:

    drp = DataRowPanel()
    for col in self.project_experiments_grid.columns:
      drp.add_component(TextBox(), column=col["id"])
    self.project_experiments_grid.add_component(drp)

You can designate your own column IDs if you set your columns in code, such as

grid.columns = [
  { "id": "A", "title": "Name", "data_key": "name" },
  { "id": "B", "title": "Address", "data_key": "address" },
  { "id": "C", "title": "Age", "data_key": "age" }
]

(But using the auto-generated column IDs is simpler.)

This worked! Thanks so much :slight_smile:

1 Like