Adding a row-number column to GWT CellTable
Asked Answered
S

2

5

I need to insert a new first-column into a CellTable, and display the RowNumber of the current row in it. What is the best way to do this in GWT?

Sideline answered 3/12, 2010 at 15:50 Comment(0)
I
4

Get the index of the element from the list wrapped by your ListDataProvider. Like this:

final CellTable<Row> table = new CellTable<Row>();
final ListDataProvider<Row> dataProvider = new ListDataProvider<Starter.Row>(getList());
dataProvider.addDataDisplay(table);

TextColumn<Row> numColumn = new TextColumn<Starter.Row>() {

    @Override
    public String getValue(Row object) {
        return Integer.toString(dataProvider.getList().indexOf(object) + 1);
    }
};

See here for the rest of the example.

Invisible answered 4/12, 2010 at 13:35 Comment(2)
I changed it to indexOf() + 1, because most users expect the first row to be "1" and not "0".Halfcock
As a software engineer I tend to disagree. But it's fine anyway :).Invisible
L
3

Solution from z00bs is wrong, because row number calculating from object's index in data List. For example, for List of Strings with elements: ["Str1", "Str2", "Str2"], the row numbers will be [1, 2, 2]. It is wrong.

This solution uses the index of row in celltable for row number.

public class RowNumberColumn extends Column {

    public RowNumberColumn() {
        super(new AbstractCell() {
            @Override
            public void render(Context context, Object o, SafeHtmlBuilder safeHtmlBuilder) {
                safeHtmlBuilder.append(context.getIndex() + 1);
            }
        });
    }

    @Override
    public String getValue(Object s) {
        return null;
    }
}

and

cellTable.addColumn(new RowNumberColumn());
Lauryn answered 22/1, 2016 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.