Auto resize row heights while sorting or filtering - nattable

I can not handle auto row heights resizing.
I tried to use AutomaticRowHeightExample, but without success.
Another inspiration was this question, but also did not worked (see my code example). If I sort/filter, in console output I can see numbers of painted rows i while creating PaintListener, but row heights are not updated.
Creating table:
public class NatTableFactory {
// another code
private NatTable createTable(Composite parent, List<TableLine> tLines, String[][] propertyNames,
PropertyToLabels[] propToLabels, TableParams params, TextMatcherEditor<TableLine>editor, boolean openableParts) {
BodyLayerStack bodyLayerStack =
new BodyLayerStack(
tLines,
tLines.get(0).getLength(),
params.getColumnIndicesForRowHeaders());
DataLayer bodyDataLayer = bodyLayerStack.getBodyDataLayer();
Integer[] rowHeights = getRowHeights(params);
if( rowHeights != null && rowHeights.length > 0 ) {
for( int i = 0; i < rowHeights.length; i++ ) {
if( rowHeights[i] != null )
bodyDataLayer.setRowHeightByPosition(i, (int) (rowHeights[i] * ApplicationSizeManager.getRowSizeCoefficient()));
}
}
Integer[] colWidths = getColumnWidths(params);
if( colWidths != null && colWidths.length > 0 ) {
for( int i = 0; i < colWidths.length; i++ )
if( colWidths[i] != null )
bodyDataLayer.setColumnWidthByPosition(i, colWidths[i]);
}
DataLayer columnHeaderDataLayer = null;
if( propertyNames != null ) {
IDataProvider columnHeaderDataProvider =
new DefaultColumnHeaderDataProvider(propertyNames[0], propToLabels[0].getPropertyToLabels());
columnHeaderDataLayer =
new DefaultColumnHeaderDataLayer(columnHeaderDataProvider);
}
//copy command: include table headers
bodyLayerStack.registerCommandHandler(new CustomCopyDataCommandHandler(bodyLayerStack.getSelectionLayer(), columnHeaderDataLayer, null, params.getColumnHeaderGroups()));
CompositeLayer composite = null;
if( propertyNames != null ) {
ColumnHeaderLayer columnHeaderLayer =
new ColumnHeaderLayer(
columnHeaderDataLayer,
bodyLayerStack,
(SelectionLayer)null);
columnHeaderLayer.addConfiguration(NatTableLayerConfigurations.getColumnHeaderLayerConfiguration(false));
SortHeaderLayer<TableLine> sortHeaderLayer =
new SortHeaderLayer<TableLine>(
columnHeaderLayer,
new GlazedListsSortModel<TableLine>(
bodyLayerStack.getSortedList(),
getSortingColumnPropAccessor(propertyNames[0]),
configRegistry,
columnHeaderDataLayer));
Integer[] hrHeights = params.getHeaderRowHeights();
if( hrHeights != null && hrHeights.length > 0 )
columnHeaderDataLayer.setRowHeightByPosition(0, (int) (hrHeights[0] * ApplicationSizeManager.getRowSizeCoefficient()));
composite = new CompositeLayer(1, 2);
composite.setChildLayer(GridRegion.COLUMN_HEADER, sortHeaderLayer, 0, 0);
composite.setChildLayer(GridRegion.BODY, bodyLayerStack, 0, 1);
} else {
composite = new CompositeLayer(1, 1);
composite.setChildLayer(GridRegion.BODY, bodyLayerStack, 0, 0);
}
composite.addConfiguration(NatTableLayerConfigurations.getCompoositeLayerConfiguration());
NatTable natTable = new NatTable(parent, composite, false);
if( params.getAutoFitColWidthIndices().size() > 0 )
registerAutoResizeColCmdHandler(natTable, composite, bodyLayerStack, params.getAutoFitColWidthIndices());
// register AutoResizeRowCommandHandler
// something wrong here?
registerAutoResizeRowCommandHandler(natTable, composite, bodyLayerStack, params.getAutoFitColWidthIndices());
setNatTableContentTooltip(natTable);
natTable.setConfigRegistry(configRegistry);
natTable.addConfiguration(new SingleClickSortConfiguration());
if(columnHeaderDataLayer!=null)
natTable.addConfiguration(NatTableLayerConfigurations.getCustomComparatorConfiguration(columnHeaderDataLayer));
natTable.addConfiguration(new DefaultNatTableStyleConfiguration());
setNatTableContextMenu(natTable, openableParts);
natTable.addConfiguration(NatTableLayerConfigurations.getNatTableConfiguration());
//
/*
natTable.addConfiguration(new DefaultNatTableStyleConfiguration()
{
{
cellPainter = new LineBorderDecorator(new AutomaticRowHeightTextPainter(5));
}
});*/
natTable.configure();
editor.setFilterator(new TextFilterator<TableLine>() {
#Override
public void getFilterStrings(List<String> baseList, TableLine element) {
for( int i = 0; i < element.getLength(); i++ )
baseList.add("" + element.getObjectByColumnForFilter(i));
}
});
editor.setMode(TextMatcherEditor.REGULAR_EXPRESSION);
bodyLayerStack.getFilterList().setMatcherEditor(editor);
NatTableContentProvider.addNatTableData(natTable, bodyLayerStack.getSelectionLayer(), bodyLayerStack.getBodyDataProvider());
return natTable;
}
// another code
}
register AutoResizeRowCommandHandler:
// in class NatTableFactory
private void registerAutoResizeRowCommandHandler(NatTable natTable, ILayer commandLayer, ILayer positionLayer, List<Integer> colPositions)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, positionLayer));
PaintListener listener = new PaintListener()
{
#Override
public void paintControl(PaintEvent e)
{
System.out.println("paintControl");
for (int i = 0; i < natTable.getRowCount(); i++)
{
System.out.println(i);
InitializeAutoResizeRowsCommand rowCommand = new InitializeAutoResizeRowsCommand(natTable, i, natTable.getConfigRegistry(), new GCFactory(
natTable));
AutoResizeRowsCommand command = new AutoResizeRowsCommand(rowCommand);
natTable.doCommand(command);
}
}
};
natTable.addPaintListener(listener);
}
BodyLayerStack:
public BodyLayerStack(List<TableLine> values, int columnCount, Integer[] columnIndicesForRowHeaders)
{
EventList<TableLine> eventList = GlazedLists.eventList(values);
TransformedList<TableLine, TableLine> rowObjectsGlazedList = GlazedLists.threadSafeList(eventList);
// this.filterList = new FilterList<>(rowObjectsGlazedList); //changed to:
// use the SortedList constructor with 'null' for the Comparator
// because the Comparator will be set by configuration
sortedList = new SortedList<>(rowObjectsGlazedList, null);
// wrap the SortedList with the FilterList
filterList = new FilterList<>(sortedList);
bodyDataProvider = new ListDataProvider<TableLine>(filterList, getColumnAccessor(columnCount));
bodyDataLayer = new DataLayer(bodyDataProvider);
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
#Override
public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) {
int columnIndex = bodyDataLayer.getColumnIndexByPosition(columnPosition);
int rowIndex = bodyDataLayer.getRowIndexByPosition(rowPosition);
if(isRowHeader(columnIndicesForRowHeaders, columnIndex))
configLabels.addLabel(NatTableFactory.RowHeaderLabel);
else
{
// get dataTypes at actual positions and add/refresh labels
String label = filterList.get(rowIndex).getObjectTypeByColumn(columnIndex);
// adjust label according to autoFitWitdh option
if(filterList.get(rowIndex).isAutoFitColWidth(columnIndex))
label += "_" + NatTableFactory.AutoFitWidthLabel;
else
label += "_" + NatTableFactory.NoAutoFitWidthLabel;
configLabels.addLabel(label);
}
}
};
bodyDataLayer.setConfigLabelAccumulator(cellLabelAccumulator);
GlazedListsEventLayer<TableLine> glazedListsEventLayer = new GlazedListsEventLayer<>(bodyDataLayer, filterList);
selectionLayer = new SelectionLayer(glazedListsEventLayer, false);
selectionLayer.setSelectionModel(getSelectionModel());
selectionLayer.addConfiguration(getSelectionConfiguration());
//
viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(new ViewportLayer(selectionLayer));
}
If I call natTable.doCommand(rowCommand) instead of natTable.doCommand(command) while registering handler, row heights are updated correctly, but table is painted repetitively, scroll bar blinks all the time.
I tried also:
private void registerAutoResizeRowCommandHandler(NatTable natTable, ILayer commandLayer, ILayer positionLayer, List<Integer> colPositions)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, positionLayer));
BodyLayerStack bodyLayerStack = (BodyLayerStack) positionLayer;
natTable.addPaintListener(
new AutoResizeRowPaintListener(
natTable,
bodyLayerStack.getViewportLayer(),
bodyLayerStack.getBodyDataLayer()));
}
Any idea what did I miss?

Well for a complete answer I would need quite some time to explain the internals of NatTable. Not sure if you are really interested in this. So I simply answer how to do it right.
With NatTable 1.6 the AutoResizeRowPaintListener was added to simplify the auto row resize task. Information about this can be found here: https://www.eclipse.org/nattable/nandn/nandn_160.php

I have got it:
in NatTableFactory:
private NatTable createTable(Composite parent, List<TableLine> tLines, String[][] propertyNames,
PropertyToLabels[] propToLabels, TableParams params, TextMatcherEditor<TableLine>editor,
boolean openableParts)
{
// another code
registerAutoResizeRowCommandHandler(natTable, composite, bodyLayerStack);
//another code
return natTable;
}
and:
private void registerAutoResizeRowCommandHandler(NatTable natTable,
CompositeLayer commandLayer, BodyLayerStack bodyLayerStack)
{
natTable.registerCommandHandler(new AutoResizeRowCommandHandler(commandLayer, bodyLayerStack));
natTable.addPaintListener(
new AutoResizeRowPaintListener(
natTable,
bodyLayerStack.getViewportLayer(),
bodyLayerStack.getBodyDataLayer()));
}
My mistake was in BodyLayerStack:
viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(new ViewportLayer(selectionLayer));
correct is:
viewportLayer = new ViewportLayer(selectionLayer);
setUnderlyingLayer(viewportLayer);
Thanks Dirk Fauth!

Related

org.eclipse.core.runtime.AssertionFailedException: assertion failed:

I am trying to create a table with ComboBoxCellEditor column. When I set value that time below exception is coming.
import org.eclipse.jface.util.Policy;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/............/
public class Test {
public static void main(String[] args) {
Shell shell = new Shell();
shell.setText("TableViewer Example");
GridLayout layout = new GridLayout();
shell.setLayout(layout);
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
composite.setLayout(new GridLayout(1, false));
Table testTable = new Table(composite, SWT.BORDER);
testTable.setLinesVisible(true);
testTable.setHeaderVisible(true);
GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, false);
tableData.heightHint = 300;
testTable.setLayoutData(tableData);
TableViewerColumn columnViewer = null;
String[] columnNames = { "Name", "Laptops" };
TableViewer testTableViewer = new TableViewer(testTable);
for (int i = 0; i < columnNames.length; i++) {
columnViewer = new TableViewerColumn(testTableViewer, SWT.LEFT);
columnViewer.getColumn().setText(columnNames[i]);
if (columnNames[i].equals("Name")) {
columnViewer.getColumn().setWidth(200);
} else if (columnNames[i].equals("Laptops")) {
columnViewer.getColumn().setWidth(300);
}
columnViewer.getColumn().setResizable(true);
columnViewer.getColumn().setMoveable(true);
columnViewer.setLabelProvider(new TestColumnLabelProvider(i));
}
testTableViewer.setContentProvider(new TestContentProvider());
testTableViewer.setColumnProperties(columnNames);
TestBean[] testBeans = new TestBean[5];
for (int i = 0; i < 5; i++) {
TestBean bean = new TestBean();
TableViewerColumn[] getTableViewerColumns =
getTableViewerColumns(testTableViewer);
for (int j = 0; j < getTableViewerColumns.length; j++) {
getTableViewerColumns[j].setEditingSupport(new
TestEditingSuport(testTableViewer, j, bean.getListOfLaptop));
}
bean.setName("Debasish" + i);
bean.setLaptop(bean.getListOfLaptop[i]);
testBeans[i] = bean;
}
testTableViewer.setInput(testBeans);
shell.open();
Display display = shell.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
public static TableViewerColumn[] getTableViewerColumns(TableViewer
tableViewer) {
TableColumn[] columns = tableViewer.getTable().getColumns();
TableViewerColumn[] viewerColumns = new TableViewerColumn[columns.length];
for (int i = 0; i < columns.length; i++) {
TableColumn tableColumn = columns[i];
viewerColumns[i] = (TableViewerColumn) tableColumn.getData(Policy.JFACE +
".columnViewer");
}
return viewerColumns;
}
}
/............./
class TestBean {
private String name;
private String laptop;
public String[] getListOfLaptop = { "Acer", "HP", "Lenovo", "Dell", "Benq"
};
//getter and setter method
}
/..................../
class TestEditingSuport extends EditingSupport {
private int m_column;
private CellEditor m_editor;
public TestEditingSuport(ColumnViewer viewer, int column,
String[] listOfTestBean) {
super(viewer);
m_column = column;
// Create the correct editor based on the column index
switch (column) {
case 0:
case 1:
m_editor = new ComboBoxCellEditor(
((TableViewer) viewer).getTable(), listOfTestBean);
break;
default:
}
}
#Override
protected CellEditor getCellEditor(Object element) {
return m_editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
TestBean bean = (TestBean) element;
Object value = null;
switch (m_column) {
case 0:
value = bean.getName();
break;
case 1:
value = bean.getLaptop();
break;
default:
}
return value;
}
#Override
protected void setValue(Object element, Object value) {
TestBean bean = (TestBean) element;
switch (m_column) {
case 0:
if (valueChanged(bean.getName(), (String) value)) {
bean.setName((String) value);
}
getViewer().update(bean, null);
break;
case 1:
int index = (Integer) value;
String laptop = bean.getListOfLaptop[index];
if (valueChanged(bean.getLaptop(), laptop)) {
bean.setLaptop(laptop);
}
getViewer().update(bean, null);
break;
default:
}
}
private boolean valueChanged(String previousValue, String currentValue) {
boolean changed = false;
if ((previousValue == null) && (currentValue != null)) {
changed = true;
} else if ((previousValue != null) && (currentValue != null) && (!previousValue.equals(currentValue))) {
changed = true;
}
return changed;
}
}
/............../
class TestContentProvider implements IStructuredContentProvider {
#Override
public Object[] getElements(Object inputElement) {
return (Object[]) inputElement;
}
}
/........................./
class TestColumnLabelProvider extends ColumnLabelProvider {
private int m_column;
public TestColumnLabelProvider(int column) {
this.m_column = column;
}
public String getText(Object element) {
String text = null;
if (element instanceof TestBean) {
TestBean testBean = (TestBean) element;
switch (m_column) {
case 0:
text = testBean.getName();
break;
case 1:
text = testBean.getLaptop();
break;
default:
}
}
return text;
}
}
/....................../
ComboCellEditor values are integer indexes in to the list of values you give it in the constructor.
Your getValue method of your EditingSupport class must return an Integer index in to the values list.
The setValue method of your EditingSupport class will be given an Integer containing the selected index.

How I can make dynamic header column and dynamic data to export to Excel/CSV/PDF using MongoDB, Spring Boot, and apache poi

I want to make export function using Spring Boot, I have data on MongoDB NoSQL, and then want to export my document on MongoDB Dynamically using Apache POI ( If any better dependency you can recommend to me).
I don't want to declare header column, entity model, etc., I want to export data dynamically as shown as in my Document database, any one can give me an example for it?
Please try these code may be help for you.
->add Gson Depandencies in porm.xml
Controller code
MasterController.java
#Autowired
MasterServiceImpl masterServiceImpl;
#GetMapping(value="/dynamicfile/{flag}/{fileType}/{fileName}")
public ResponseEntity<InputStreamResource> downloadsFiles(#PathVariable("flag") int flag,#PathVariable("fileType") String fileType,#PathVariable("fileName") String fileName) throws IOException{
List<?> objects=new ArrayList<>();
if(flag==1) {
objects=masterServiceImpl.getData();
}
ByteArrayInputStream in = masterServiceImpl.downloadsFiles(objects,fileType);
HttpHeaders headers = new HttpHeaders();
if(fileType.equals("Excel")) {
headers.add("Content-Disposition", "attachment; filename="+fileName+".xlsx");
}else if(fileType.equals("Pdf")){
headers.add("Content-Disposition", "attachment; filename="+fileName+".pdf");
}else if(fileType.equals("Csv")) {
headers.add("Content-Disposition", "attachment; filename="+fileName+".csv");
}
return ResponseEntity.ok().headers(headers).body(new InputStreamResource(in));
}
Service code :
MasterServiceImpl.java
public static List<HashMap<Object, Object>> getListOfObjectToListOfHashMap(List<?> objects) {
List<HashMap<Object,Object>> list=new ArrayList<>();
for(int i=0;i<objects.size();i++) {
HashMap<Object,Object> map=new HashMap<>();
String temp=new Gson().toJson(objects.get(i)).toString();
String temo1= temp.substring(1, temp.length()-1);
String[] temp2=temo1.split(",");
for(int j=-1;j<temp2.length;j++) {
if(j==-1) {
map.put("SrNo",i+1);
}else {
String tempKey=temp2[j].toString().split(":")[0].toString();
String tempValue=temp2[j].toString().split(":")[1].toString();
char ch=tempValue.charAt(0);
if(ch=='"') {
map.put(tempKey.substring(1, tempKey.length()-1), tempValue.substring(1, tempValue.length()-1));
}else {
map.put(tempKey.substring(1, tempKey.length()-1), tempValue);
}
}
}
list.add(map);
}
return list;
}
public static ByteArrayInputStream downloadsFiles(List<?> objects,String fileType) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<HashMap<Object, Object>> list = getListOfObjectToListOfHashMap(objects);
String[] COLUMNs = getColumnsNameFromListOfObject(objects);
try{
if(fileType.equals("Excel")) {
generateExcel(list, COLUMNs,out);
}else if(fileType.equals("Pdf")) {
generatePdf(list, COLUMNs,out);
}else if(fileType.equals("Csv")) {
generatePdf(list, COLUMNs,out);
}
}catch(Exception ex) {
System.out.println("Error occurred:"+ ex);
}
return new ByteArrayInputStream(out.toByteArray());
}
public static final String[] getColumnsNameFromListOfObject(List<?> objects) {
String strObjects=new Gson().toJson(objects.get(0)).toString();
String[] setHeader= strObjects.substring(1, strObjects.length()-1).split(",");
String header="SrNo";
for(int i=0;i<setHeader.length;i++) {
String str=setHeader[i].toString().split(":")[0].toString();
header=header+","+str.substring(1, str.length()-1);
}
return header.split(",");
}
public static final void generateExcel(List<HashMap<Object, Object>> list, String[] COLUMNs,ByteArrayOutputStream out) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Excelshit");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
Row headerRow = sheet.createRow(0);
for (int col = 0; col < COLUMNs.length; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(COLUMNs[col]);
cell.setCellStyle(headerCellStyle);
}
int rowIdx = 1;
for(int k = 0; k < list.size(); k++){
Row row =sheet.createRow(rowIdx++);
for (Map.Entry<Object, Object> entry : list.get(k).entrySet()){
Object key = entry.getKey();
Object value = entry.getValue();
for (int col = 0; col < COLUMNs.length; col++) {
if(key.toString().equals(COLUMNs[col].toString())) {
row.createCell(col).setCellValue(value.toString());
}
}
}
}
workbook.write(out);
System.out.println(workbook);
}
private static final void generatePdf(List<HashMap<Object, Object>> list, String[] COLUMNs,ByteArrayOutputStream out) throws DocumentException {
Document document = new Document();
com.itextpdf.text.Font headerFont =FontFactory.getFont(FontFactory.HELVETICA_BOLD,8);
com.itextpdf.text.Font dataFont =FontFactory.getFont(FontFactory.TIMES_ROMAN,8);
PdfPCell hcell=null;
PdfPTable table = new PdfPTable(COLUMNs.length);
for (int col = 0; col < COLUMNs.length; col++) {
hcell = new PdfPCell(new Phrase(COLUMNs[col], headerFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
}
for(int index = 0; index < list.size(); index++){
PdfPCell cell = null;
for (Map.Entry<Object, Object> entry : list.get(index).entrySet()){
Object key = entry.getKey();
Object value = entry.getValue();
for (int col = 0; col < COLUMNs.length; col++) {
if(key.toString().equals(COLUMNs[col].toString())) {
cell = new PdfPCell(new Phrase(value.toString(),dataFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
}
table.addCell(cell);
}
}
PdfWriter.getInstance(document, out);
document.open();
document.add(table);
document.close();
}
public List<TblDepartment> getData() {
List<TblDepartment> list = new ArrayList<>();
departmentRepository.findAll().forEach(list::add);
return list;
}

C# Web Form: GridView disappears while MessageBox is showing

I have 3 GridViews, each inside a separate tab. Every row in the GridView is associated with a LinkButton, and when it's clicked a MessageBox are popping up, showing the content on that particular row.
The problem is that when the MessageBox pops up the GridView disappears, and when MessageBox is closed GridView then comes back.
This problem doesn't occur if GridView is used without any tabs and is placed outside the TabControl. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
TabControl TheTabCtrl = new TabControl("InfoTabCtrl");
for (var i = 0; i < 3; i++)
{
GridView newGridView = new GridView();
//generate dynamic id
newGridView.ID = String.Concat("GridView", i);
newGridView.AutoGenerateColumns = false;
newGridView.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
//if (!this.IsPostBack)
//{
BoundField bfield = new BoundField();
bfield.HeaderText = "Id";
bfield.DataField = "Id";
newGridView.Columns.Add(bfield);
bfield = new BoundField();
bfield.HeaderText = "Name";
bfield.DataField = "Name";
newGridView.Columns.Add(bfield);
TemplateField tfield = new TemplateField();
tfield.HeaderText = "Country";
newGridView.Columns.Add(tfield);
tfield = new TemplateField();
tfield.HeaderText = "View";
newGridView.Columns.Add(tfield);
//}
this.BindGrid(newGridView, i);
string myString = i.ToString();
TabPage BasicPage1 = new TabPage(myString, myString);
BasicPage1.Controls.Add(newGridView);
TheTabCtrl.Tabs.Add(BasicPage1);
}
if (!this.IsPostBack)
{
string value = Request.Form[TheTabCtrl.Id + "_SelectedTab"];
if (!string.IsNullOrEmpty(value))
{
try
{
TheTabCtrl.SelectedTab = TheTabCtrl.Tabs.IndexOf(TheTabCtrl.Tabs.Where(x => x.Id == value).First());
}
catch
{
}
}
}
form1.Controls.Add(TheTabCtrl.GetControl);
}
private void BindGrid(GridView newGridView, int id)
{
string[][,] jaggedArray = new string[3][,]
{
new string[,] { {"John Hammond", "United States"}, {"Mudassar Khan", "India"}, {"Suzanne Mathews", "France"}, {"Robert Schidner", "Russia"} },
new string[,] { {"Zoey Melwick", "New Zeeland"}, {"Bryan Robertson", "England"}, {"Beth Stewart", "Australia"}, {"Amanda Rodrigues", "Portugal"} },
new string[,] { {"Glenda Becker", "Germany"}, {"Despoina Athanasiadis", "Greece"}, {"Alexandra López", "Spain"}, {"David Bouchard", "Canada"} }
};
for (int row = 0; row < jaggedArray.Length; row++)
{
if (id != row) continue;
DataTable dt = new DataTable();
// Share the same headlines
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
for (int pair = 0; pair < jaggedArray[row].Length / 2; pair++)
{
dt.Rows.Add(pair + 1, jaggedArray[row][pair, 0], jaggedArray[row][pair, 1]);
}
string myPage = string.Concat(row, "page");
string myString = row.ToString();
newGridView.DataSource = dt;
newGridView.DataBind();
}//End for Row
}//BindGrid
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtCountry = new TextBox();
txtCountry.ID = "txtCountry";
txtCountry.Text = (e.Row.DataItem as DataRowView).Row["Country"].ToString();
e.Row.Cells[1].Width = 200;
e.Row.Cells[2].Controls.Add(txtCountry);
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[3].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[1].Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + " Name: " + name + " Country: " + country + "')", true);
}
So how can I show a MessageBox without GridView disappearing?

Copying fields in iTextSharp 5.4.5.0

I was under the impression that it is now possible to copy AcroFields using PdfCopy. In the release notes for iText 5.4.4.0 this is listed as possible now. However, when I try to do so it appears all the annotations (I think I am using that term correctly, still fairly new to iText...) for the fields are stripped out. It looks like the fields are there (meaning I can see the blue boxes that indicate an editable field), but they are not editable. If I try to bring the PDF up in Acrobat I get a message saying that "there are no fields, would you like Acrobat to discover them?" and most are found and marked and fields properly (check boxes aren't, but the text fields are).
I assume there is an additional step somewhere along the lines to re-add the annotations to the PdfCopy object, but I do not see a way to get the annotations from the PdfReader. I also cannot seem to find any documentation on how to do this (since AcroFields were for so long not supported in PdfCopy most of what I find is along that vein).
Due to sensitivity I cannot provide a copy of the PDF's in question, but using an altered version of a test program used earlier you can see the issue with the following code. It should generate a table with some check boxes in the four right columns. If I use the exact same code with PdfCopyFields in the MergePdfs method instead of PdfCopy it works as expected. This code does not produce any text fields, but in my main project they are part of the original parent PDF that is used as a template.
(Sorry for the long example, it has been cherry picked from a much larger application. You will need a PDF with a field named "TableStartPosition" somewhere in it and update RunTest with the correct paths for your local machine to get this to work.)
Has the PdfCopy functionality not made it into iTextSharp yet? I am using version 5.4.5.0.
class Program
{
Stream _pdfTemplateStream;
MemoryStream _pdfResultStream;
PdfReader _pdfTemplateReader;
PdfStamper _pdfResultStamper;
static void Main(string[] args)
{
Program p = new Program();
try
{
p.RunTest();
}
catch (Exception f)
{
Console.WriteLine(f.Message);
Console.ReadLine();
}
}
internal void RunTest()
{
FileStream fs = File.OpenRead(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\CoverPage.pdf");
_pdfTemplateStream = fs;
_pdfResultStream = new MemoryStream();
//PDFTemplateStream = new FileStream(_templatePath, FileMode.Open);
_pdfTemplateReader = new PdfReader(_pdfTemplateStream);
_pdfResultStamper = new PdfStamper(_pdfTemplateReader, _pdfResultStream);
#region setup objects
List<CustomCategory> Categories = new List<CustomCategory>();
CustomCategory c1 = new CustomCategory();
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[2]);
Categories.Add(c1);
CustomCategory c2 = new CustomCategory();
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[0]);
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
Categories.Add(c2);
List<CustomObject> Items = new List<CustomObject>();
CustomObject co1 = new CustomObject();
co1.Category = c1;
co1.Title = "Object 1";
Items.Add(co1);
CustomObject co2 = new CustomObject();
co2.Category = c2;
co2.Title = "Object 2";
Items.Add(co2);
#endregion
FillCoverPage(Items);
_pdfResultStamper.Close();
_pdfTemplateReader.Close();
List<MemoryStream> pdfStreams = new List<MemoryStream>();
pdfStreams.Add(new MemoryStream(_pdfResultStream.ToArray()));
MergePdfs(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\Outfile.pdf", pdfStreams);
_pdfResultStream.Dispose();
_pdfTemplateStream.Dispose();
}
internal void FillCoverPage(List<CustomObject> Items)
{
//Before we start we need to figure out where to start adding the table
var fieldPositions = _pdfResultStamper.AcroFields.GetFieldPositions("TableStartPosition");
if (fieldPositions == null)
{ throw new Exception("Could not find the TableStartPosition field. Unable to determine point of origin for the table!"); }
_pdfResultStamper.AcroFields.RemoveField("TableStartPosition");
var fieldPosition = fieldPositions[0];
// Get the position of the field
var targetPosition = fieldPosition.position;
//First, get all the available card sizes
List<string> availableSizes = CustomCategory.AvailableSizes;
//Generate a table with the number of available card sizes + 1 for the device name
PdfPTable table = new PdfPTable(availableSizes.Count + 1);
float[] columnWidth = new float[availableSizes.Count + 1];
for (int y = 0; y < columnWidth.Length; y++)
{
if (y == 0)
{ columnWidth[y] = 320; }
else
{ columnWidth[y] = 120; }
}
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
PdfContentByte canvas;
List<PdfFormField> checkboxes = new List<PdfFormField>();
//Build the header row
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
//Insert the global check boxes
PdfPCell[] globalRow = new PdfPCell[availableSizes.Count + 1];
Phrase tPhrase = new Phrase("Select/Unselect All");
PdfPCell tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
tCell.AddElement(tPhrase);
globalRow[0] = tCell;
for (int x = 0; x < availableSizes.Count; x++)
{
tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.Global.chk{0}", availableSizes[x].Replace(".", ""));
//f.FieldName = fieldName;
string js = string.Format("hideAll(event.target, '{0}');", availableSizes[x].Replace(".", ""));
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
globalRow[x + 1] = tCell;
checkboxes.Add(f);
}
table.Rows.Add(new PdfPRow(globalRow));
int status = 0;
int pageNum = 1;
for (int itemIndex = 0; itemIndex < Items.Count; itemIndex++)
{
tCell = new PdfPCell();
Phrase p = new Phrase(Items[itemIndex].Title);
tCell.AddElement(p);
tCell.HorizontalAlignment = Element.ALIGN_LEFT;
PdfPCell[] cells = new PdfPCell[availableSizes.Count + 1];
cells[0] = tCell;
for (int availCardSizeIndex = 0; availCardSizeIndex < availableSizes.Count; availCardSizeIndex++)
{
if (Items[itemIndex].Category.CategorySizesInUse.Contains(availableSizes[availCardSizeIndex]))
{
string str = availableSizes[availCardSizeIndex];
tCell = new PdfPCell();
tCell.PaddingLeft = 10f;
tCell.PaddingRight = 10f;
cells[availCardSizeIndex + 1] = tCell;
cells[availCardSizeIndex].HorizontalAlignment = Element.ALIGN_CENTER;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.chk{0}.{1}", availableSizes[availCardSizeIndex].Replace(".", ""), itemIndex + 1);
//f.FieldName = fieldName; <-- This causes the checkbox to be double-named (i.e. InkSaver.Global.chk0.InkSaver.Global.chk0
string js = string.Format("hideCardSize(event.target, {0}, '{1}');", itemIndex + 1, availableSizes[availCardSizeIndex]);
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
checkboxes.Add(f);
}
else
{
//Add a blank cell
tCell = new PdfPCell();
cells[availCardSizeIndex + 1] = tCell;
}
}
//Test if the column text will fit
table.Rows.Add(new PdfPRow(cells));
canvas = _pdfResultStamper.GetUnderContent(pageNum);
ColumnText ct2 = new ColumnText(canvas);
ct2.AddElement(new PdfPTable(table));
ct2.Alignment = Element.ALIGN_LEFT;
ct2.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
status = ct2.Go(true);
if ((status != ColumnText.NO_MORE_TEXT) || (itemIndex == (Items.Count - 1)))
{
ColumnText ct3 = new ColumnText(canvas);
ct3.AddElement(table);
ct3.Alignment = Element.ALIGN_LEFT;
ct3.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
ct3.Go();
foreach (PdfFormField f in checkboxes)
{
_pdfResultStamper.AddAnnotation(f, pageNum);
}
checkboxes.Clear();
if (itemIndex < (Items.Count - 1))
{
pageNum++;
_pdfResultStamper.InsertPage(pageNum, _pdfTemplateReader.GetPageSize(1));
table = new PdfPTable(availableSizes.Count + 1);
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
}
}
}
}
private PdfPCell[] GetTableHeaderRow(List<string> AvailableSizes)
{
PdfPCell[] sizeHeaders = new PdfPCell[AvailableSizes.Count + 1];
Phrase devName = new Phrase("Device Name");
PdfPCell deviceHeader = new PdfPCell(devName);
deviceHeader.HorizontalAlignment = Element.ALIGN_CENTER;
deviceHeader.BackgroundColor = BaseColor.GRAY;
sizeHeaders[0] = deviceHeader;
for (int x = 0; x < AvailableSizes.Count; x++)
{
PdfPCell hCell = new PdfPCell(new Phrase(AvailableSizes[x]));
hCell.HorizontalAlignment = Element.ALIGN_CENTER;
hCell.BackgroundColor = BaseColor.GRAY;
sizeHeaders[x + 1] = hCell;
}
return sizeHeaders;
}
public void MergePdfs(string filePath, List<MemoryStream> pdfStreams)
{
//Create output stream
FileStream outStream = new FileStream(filePath, FileMode.Create);
Document document = null;
if (pdfStreams.Count > 0)
{
try
{
int PageCounter = 0;
//Create Main reader
PdfReader reader = new PdfReader(pdfStreams[0]);
PageCounter = reader.NumberOfPages;//This is if we have multiple pages in the cover page, we need to adjust the offset.
//rename fields in the PDF. This is required because PDF's cannot have more than one field with the same name
RenameFields(reader, PageCounter++);
//Create Main Doc
document = new Document(reader.GetPageSizeWithRotation(1));
//Create main writer
PdfCopy Writer = new PdfCopy(document, outStream);
//PdfCopyFields Writer = new PdfCopyFields(outStream);
//Open document for writing
document.Open();
////Add pages
Writer.AddDocument(reader);
//For each additional pdf after first combine them into main document
foreach (var PdfStream in pdfStreams.Skip(1))
{
PdfReader reader2 = new PdfReader(PdfStream);
//rename PDF fields
RenameFields(reader2, PageCounter++);
// Add content
Writer.AddDocument(reader);
}
//Writer.AddJavaScript(PostProcessing.GetSuperscriptJavaScript());
Writer.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (document != null)
document.Close();
foreach (var Strm in pdfStreams)
{
try { if (null != Strm) Strm.Dispose(); }
catch { }
}
//pdfStamper.Close();
outStream.Close();
}
}
}
private void RenameFields(PdfReader reader, int PageNum)
{
int tempPageNum = 1;
//rename all fields
foreach (string field in reader.AcroFields.Fields.Keys)
{
if (((reader.AcroFields.GetFieldType(field) == 1) || (reader.AcroFields.GetFieldType(field) == 2)) && (field.StartsWith("InkSaver")))
{
//This is a InkSaver button, set the name so its subclassed
string classPath;
if (reader.AcroFields.GetFieldType(field) == 2)
{
classPath = field.Substring(0, field.LastIndexOf("."));
if (field.StartsWith("InkSaver.chk"))
{
int a = field.LastIndexOf(".");
string sub = field.Substring(a + 1, (field.Length - a - 1));
int pageNum = int.Parse(sub);
int realPageNum = pageNum + tempPageNum;//PostProcessing.Instance.CoverPageLength;
PageNum = realPageNum;
}
}
else
{
classPath = field.Substring(0, field.LastIndexOf("."));
}
string newID = classPath + ".page" + PageNum.ToString();
bool ret = reader.AcroFields.RenameField(field, newID);
}
else
{
reader.AcroFields.RenameField(field, field + "_" + PageNum.ToString());// field + Guid.NewGuid().ToString("N"));
}
}
}
}
public class ChildFieldEvent : IPdfPCellEvent
{
protected PdfWriter writer;
protected PdfFormField parent;
protected string checkBoxName;
internal ChildFieldEvent(PdfWriter writer, PdfFormField parent, string CheckBoxName)
{
this.writer = writer;
this.parent = parent;
this.checkBoxName = CheckBoxName;
}
public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb)
{
createCheckboxField(rect);
}
private void createCheckboxField(Rectangle rect)
{
RadioCheckField bt = new RadioCheckField(this.writer, rect, this.checkBoxName, "Yes");
bt.CheckType = RadioCheckField.TYPE_SQUARE;
bt.Checked = true;
this.parent.AddKid(bt.CheckField);
}
}
internal class CustomCategory
{
internal static List<string> AvailableSizes
{
get
{
List<string> retVal = new List<string>();
retVal.Add("1");
retVal.Add("2");
retVal.Add("3");
retVal.Add("4");
return retVal;
}
}
internal CustomCategory()
{
CategorySizesInUse = new List<string>();
}
internal List<string> CategorySizesInUse { get; set; }
}
internal class CustomObject
{
internal string Title { get; set; }
internal CustomCategory Category { get;set; }
}
Please take a look at the MergeForms example. Your example is too long for me to read, but at first sight, I'm missing the following line:
copy.setMergeFields();
By the way, in MergeForms2, the fields are also renamed before the form is merged.

CustomdataGrid is not being displayed in the browser

I have a custom datagrid which is defined as follows
public class CustomDataGrid<T> extends DataGrid<T> {
private static final int PAGE_SIZE = 10;
public CustomDataGrid(ProvidesKey<T> keysProvider) {
super(PAGE_SIZE, keysProvider);
}
public CustomDataGrid() {
super(PAGE_SIZE);
}
public void redrawRow(int absRowIndex) {
int relRowIndex = absRowIndex - getPageStart();
checkRowBounds(relRowIndex);
setRowData(absRowIndex, Collections.singletonList(getVisibleItem(relRowIndex)));
}
}
I am using ui binder and in my xml file I have defined the elements as follows
<com:CustomDataGrid ui:field="commissionListDataGrid"></com:CustomDataGrid>
Now the custom datagrid is initialised as follows
#UiField
CustomDataGrid commissionListDataGrid;
private final Set<Long> showingFriends = new HashSet<Long>();
private Column<ServiceCategorywiseCommissionDetails, String> viewFriendsColumn;
private Column<ServiceCategorywiseCommissionDetails, String> serviceType;
public ZoneCommissionListView() {
commissionListDataGrid = new CustomDataGrid<ServiceCategorywiseCommissionDetails>(new ProvidesKey<ServiceCategorywiseCommissionDetails>() {
#Override
public Object getKey(ServiceCategorywiseCommissionDetails item) {
return item == null ? null : item.getId();
}
});
commissionListDataGrid.setWidth("100%");
commissionListDataGrid.setEmptyTableWidget(new Label("Empty data"));
commissionListDataGrid.setHeight("100%");
// commissionListLayoutPanel = new SimpleLayoutPanel();
initCommissionListDataGrid();
// commissionListLayoutPanel.add(commissionListDataGrid);
//RootLayoutPanel.get().add(commissionListLayoutPanel);
}
#Override
public Widget asWidget() {
return this.widget;
}
#Override
public void setUiHandlers(ZoneCommissionListUiHandlers uiHandlers) {
this.uiHandlers = uiHandlers;
}
public void initCommissionListDataGrid() {
// View friends.
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(").appendEscaped(object).appendHtmlConstant(")");
return sb.toSafeHtml();
}
};
viewFriendsColumn = new Column<ServiceCategorywiseCommissionDetails, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
if (showingFriends.contains(object.getId())) {
return "-";
} else {
return "+";
}
}
};
viewFriendsColumn.setFieldUpdater(new FieldUpdater<ServiceCategorywiseCommissionDetails, String>() {
#Override
public void update(int index, ServiceCategorywiseCommissionDetails object, String value) {
if (showingFriends.contains(object.getId())) {
showingFriends.remove(object.getId());
} else {
showingFriends.add(object.getId());
}
// Redraw the modified row.
commissionListDataGrid.redrawRow(index);
}
});
// First name.
serviceType = new Column<ServiceCategorywiseCommissionDetails, String>(new TextCell()) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
return object.getServiceType();
}
};
commissionListDataGrid.setTableBuilder(new CustomTableBuilder());
commissionListDataGrid.setHeaderBuilder(new CustomHeaderBuilder());
// commissionListDataGrid.setFooterBuilder(new CustomFooterBuilder());
// GWT.log("list size is " + ContactDatabase.get().getDataProvider().getList().size());
// commissionListDataGrid.setRowData(ContactDatabase.get().getDataProvider().getList());
// Button button = new Button();
// button.setText("hello");
// commissionListLayoutPanel.add(commissionListDataGrid);
this.widget = uiBinder.createAndBindUi(this);
}
private class CustomTableBuilder extends AbstractCellTableBuilder<ServiceCategorywiseCommissionDetails> {
private final String childCell = " ";
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
#SuppressWarnings("deprecation")
public CustomTableBuilder() {
super(commissionListDataGrid);
// Cache styles for faster access.
Style style = commissionListDataGrid.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
public void buildRowImpl(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex) {
buildServiceTypeRow(rowValue, absRowIndex, false);
GWT.log("Inside build row impl");
// Display list of friends.
if (showingFriends.contains(rowValue.getId())) {
TableRowBuilder row = startRow();
TableCellBuilder th = row.startTH();
th.text("").endTH();
TableCellBuilder th2 = row.startTH();
th2.text("Service Name").endTH();
TableCellBuilder th3 = row.startTH();
th3.text("SuperZone Commission").endTH();
TableCellBuilder th4 = row.startTH();
th4.text("Zone Commission").endTH();
row.endTR();
List<ServiceCommissionDetails> friends = rowValue.getServiceCommissionDetails();
for (ServiceCommissionDetails friend : friends) {
buildServiceCommissionDetailRow(friend, absRowIndex, true);
}
}
}
#SuppressWarnings("deprecation")
private void buildServiceTypeRow(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service Type row");
SelectionModel<? super ServiceCategorywiseCommissionDetails> selectionModel = commissionListDataGrid.getSelectionModel();
boolean isSelected = (selectionModel == null || rowValue == null) ? false : selectionModel.isSelected(rowValue);
boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
// Calculate the cell styles.
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
if (isFriend) {
cellStyles += childCell;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
td = row.startTD();
td.className(cellStyles);
if (!isFriend) {
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
renderCell(td, createContext(1), viewFriendsColumn, rowValue);
}
td.endTD();
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (isFriend) {
td.text(rowValue.getServiceType());
} else {
renderCell(td, createContext(2), serviceType, rowValue);
}
td.endTD();
// Last name column.
row.endTR();
}
#SuppressWarnings("deprecation")
private void buildServiceCommissionDetailRow(ServiceCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service commission detail row");
// Calculate the row styles.
// boolean isSelected = (selectionModel == null || rowValue == null)
// ? false : selectionModel.isSelected(rowValue);
// boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
// if (isSelected) {
// trClasses.append(selectedRowStyle);
// }
// Calculate the cell styles.
String cellStyles = cellStyle;
// cellStyles += selectedCellStyle;
cellStyles += childCell;
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getServiceName());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getSuperZoneCommission());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getZoneCommission());
td.endTD();
// Last name column.
row.endTR();
}
}
private class CustomHeaderBuilder extends AbstractHeaderOrFooterBuilder<ServiceCategorywiseCommissionDetails> {
private Header<String> firstNameHeader = new TextHeader("Co mmission List");
public CustomHeaderBuilder() {
super(commissionListDataGrid, false);
setSortIconStartOfLine(false);
}
#Override
protected boolean buildHeaderOrFooterImpl() {
Style style = commissionListDataGrid.getResources().style();
String groupHeaderCell = "Header Cell";
// Add a 2x2 header above the checkbox and show friends columns.
TableRowBuilder tr = startRow();
tr.startTH().colSpan(2).rowSpan(2).className(style.header() + " " + style.firstColumnHeader());
tr.endTH();
/*
* Name group header. Associated with the last name column, so clicking on the group header sorts by last name.
*/
// Get information about the sorted column.
ColumnSortList sortList = commissionListDataGrid.getColumnSortList();
ColumnSortInfo sortedInfo = (sortList.size() == 0) ? null : sortList.get(0);
Column<?, ?> sortedColumn = (sortedInfo == null) ? null : sortedInfo.getColumn();
boolean isSortAscending = (sortedInfo == null) ? false : sortedInfo.isAscending();
// Add column headers.
tr = startRow();
buildHeader(tr, firstNameHeader, serviceType, sortedColumn, isSortAscending, false, false);
tr.endTR();
return true;
}
private void buildHeader(TableRowBuilder out, Header<?> header, Column<ServiceCategorywiseCommissionDetails, ?> column, Column<?, ?> sortedColumn, boolean isSortAscending, boolean isFirst,
boolean isLast) {
// Choose the classes to include with the element.
Style style = commissionListDataGrid.getResources().style();
boolean isSorted = (sortedColumn == column);
StringBuilder classesBuilder = new StringBuilder(style.header());
if (isFirst) {
classesBuilder.append(" " + style.firstColumnHeader());
}
if (isLast) {
classesBuilder.append(" " + style.lastColumnHeader());
}
// if (column.isSortable()) {
// classesBuilder.append(" " + style.sortableHeader());
// }
if (isSorted) {
classesBuilder.append(" " + (isSortAscending ? style.sortedHeaderAscending() : style.sortedHeaderDescending()));
}
// Create the table cell.
TableCellBuilder th = out.startTH().className(classesBuilder.toString());
// Associate the cell with the column to enable sorting of the
// column.
enableColumnHandlers(th, column);
// Render the header.
Context context = new Context(0, 2, header.getKey());
renderSortableHeader(th, context, header, isSorted, isSortAscending);
// End the table cell.
th.endTH();
}
}
public void setCommissionListDataGrid(ListDataProvider<ServiceCategorywiseCommissionDetails> dataProvider) {
GWT.log("inside set commissionListDataGrid size is " + dataProvider.getList().size());
commissionListDataGrid.setRowData(dataProvider.getList());
}
And I have a method in the presenter which calls the method set CommissionListDataGrid and sets its row value.
While doing this the data grid is not displayed. However if i add simplelayoutpanel in the following way in the constructor 'ZoneCommissionListView()'
RootPanel.get().add(commissionListLayoutPanel);
Then the data grid is displayed .What exactly am I missing .Any suggestion would be appreciated
DataGrid requires to be put in a LayoutPanel or Panel that implements
the ProvidesResize interface to be visible.
Source
And the SimpelLayoutPanel which you tested also implements the ProvidesResize Interface.