Monday, December 29, 2008

GWT : How to clear HTML Table completely?

This is the way many programmers cleans HTML Table (FlexTable and Grid are subclass of HTML Table). 

private FlexTable table = new FlexTable();

int i = 0;
for (List row : result) {
   int j = 0;
   for (String element : row) {
      table.setHTML(i, j, element);
      j++;
   }
   i++;
}

Programmer could also add widgets to the Flex table.

table.setWidget(i, j, new Label("Name"));

And to clear the table, programmer call clear() method of HTML table.

table.clear() 

Description of the clear() method says "it removes all widgets from this table, but does not remove other HTML or text contents of cells". So it will remove the label added to the Table but not HTML added in the for loop. Many times it leads you to wrong result.

For example: Lets assume table (4 x 4) contains 'A' in each cell 

AAAA
AAAA
AAAA
AAAA

Now programmer called table.clear() and write (3x3) elements with data 'B'. If he tries to print the complete table, he will see following result which is not expected.

BBBA
BBBA
BBBA
AAAA

How can we eliminate this problem? Solution : remove all the row one by one before adding new data to table.

for (; table.getRowCount() > 0; ) {
   table.removeRow(0);
}

Feel free to comment on this blog.

2 comments:

Ashok said...

what is table here. is it ID or html tag? How it can be used in javascript?

Anonymous said...

I know it's old, but this page came up on a google search.

You could just do a table.resize(0,0)...