This is a migrated thread and some comments may be shown as answers.

Table - adjust column width to content

12 Answers 961 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Matthias
Top achievements
Rank 1
Matthias asked on 04 May 2011, 03:33 PM
Hi,

I am using my own custom printpreview in which I show basically a Telerik.Windows.Documents.Model.Table.

The table itself stretches to fit the page, but all columns have equal width, but I would like them to fit their content.

I can only assign  a PreferredWidth to a distinct TableCell.

Is there a possibility to have the Columns adjust their width to their content?

12 Answers, 1 is accepted

Sort by
0
Boby
Telerik team
answered on 06 May 2011, 12:39 PM
Hi Matthias,

You can set preferred width of a table column by setting PreferredWidth property of corresponding TableGridColumn:
table.Grid.Columns[index].PreferredWidth = new TableWidthUnit(TableWidthUnitType.Auto);
TableGrid and TableGridColumn are abstractions needed to cover the cases with merged columns/rows.

Don't hesitate to contact us if you have other questions.


Kind regards,
Boby
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Matthias
Top achievements
Rank 1
answered on 06 May 2011, 01:37 PM

I am using the following extension method to convert a RadGridView to a table to use for printing.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Telerik.Windows.Controls;
using Telerik.Windows.Documents.Layout;
using Telerik.Windows.Documents.Model;
  
namespace xyz
{
    public static class RadGridViewExtensions
    {
  
        public static RadDocument CreateDocument(this RadGridView grid, double width, double height)
        {
            List<GridViewBoundColumnBase> columns = (from c in grid.Columns.OfType<GridViewBoundColumnBase>()
                                                     orderby c.DisplayIndex
                                                     select c).ToList();
  
            Table table = new Table();
            table.PreferredWidth = new TableWidthUnit((float)width);
            table.LayoutMode = TableLayoutMode.AutoFit;
  
            RadDocument document = new RadDocument();
            document.LayoutMode = DocumentLayoutMode.Paged;
            document.ParagraphDefaultSpacingAfter = document.ParagraphDefaultSpacingBefore = 0;
            document.PageViewMargin = new SizeF(10, 10);
            document.SectionDefaultPageMargin = new Padding(0, 0, 0, 0);
  
            if (document.DefaultPageLayoutSettings.Width != (float)width)
                document.DefaultPageLayoutSettings.Width = (float)width;
  
            if (document.DefaultPageLayoutSettings.Height != (float)height)
                document.DefaultPageLayoutSettings.Height = (float)height;
  
            // This is required so the document can arrange its sub-parts
            document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
            document.Arrange(new RectangleF(PointF.Empty, document.DesiredSize));
  
            Section section = new Section();
            section.Blocks.Add(table);
            document.Sections.Add(section);
  
            if (grid.ShowColumnHeaders)
            {
                TableRow headerRow = new TableRow();
  
                for (int i = 0; i < columns.Count(); i++)
                {
                    TableCell cell = new TableCell();
                    AddCellValue(cell, columns[i].UniqueName);
                    cell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Auto);
                    headerRow.Cells.Add(cell);
                }
  
                table.Rows.Add(headerRow);
            }
  
                AddDataRows(table, grid.Items, columns, grid);
  
            return document;
        }
  
        private static void AddDataRows(Table table, IList items, IList<GridViewBoundColumnBase> columns, RadGridView grid)
        {
            for (int i = 0; i < items.Count; i++)
            {
                TableRow row = new TableRow();
  
                for (int j = 0; j < columns.Count(); j++)
                {
                    TableCell cell = new TableCell();
  
                    object value = columns[j].GetValueForItem(items[i]);
  
                    AddCellValue(cell, value != null ? value.ToString() : string.Empty);
  
                    cell.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Auto);
  
                    row.Cells.Add(cell);
                }
  
                table.Rows.Add(row);
            }
        }
  
        private static void AddCellValue(TableCell cell, string value)
        {
            Paragraph paragraph = new Paragraph();
            cell.Blocks.Add(paragraph);
  
            Span span = new Span();
            span.Text = value;
            span.FontSize = 10;
  
            paragraph.Inlines.Add(span);
        }
    }
}


The table is created succefully, but all columns have equal size. I tried to set the width as you suggested, but it still does not work :(

Any help is appreciated ;)

Kind regards,
Matthias

0
Iva Toteva
Telerik team
answered on 11 May 2011, 03:29 PM
Hello Matthias,

Thank you for getting to us with the sample code.
However, I tested it and it seemed to work as expected. Please find attached a demo, which exports the GridView to a RadDocument and shows the document in a RadRichTextBox or shows a print preview right away.
Note that the table columns are resized only when there is a word in one of the columns that needs more space than the current width of the column.
I hope that helps.

All the best,
Iva
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Matthias
Top achievements
Rank 1
answered on 12 May 2011, 11:01 AM
Thanks, that helped much.

0
tchapo
Top achievements
Rank 1
answered on 23 Jun 2011, 11:49 PM
Hi Boby,

I am having similar issue using raddocument to export radgridview to pdf or print its content. the columns are narrow and any attempts to change the properties did not work. I even use the sample code you provided to Mathias but same issue. I tried incorporating the following line you pasted but no luck. i am getting index out of range.

table.Grid.Columns[index].PreferredWidth = new TableWidthUnit(TableWidthUnitType.Auto);

Could you please modify the sample code to include this line?

Regards,
Tchapo.
0
Boby
Telerik team
answered on 30 Jun 2011, 06:45 AM
Hello Tchapo,
Could you please verify that index is not bigger than the count of the columns in the table? if this doesn't help, could you please send us a sample project that reproduces the problem, or at least share more details about your scenario and the stack trace of the exception?

Regards, Boby
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
tchapo
Top achievements
Rank 1
answered on 11 Jul 2011, 10:43 PM

Hi Boby,

The index is not bigger than the columns count of the table.
The code I am using is nearly the same as the one posted by Matthias and is added below.
The RadGridView I am trying to print or export to PDF has about 25 columns. When I remove most of the columns and only keep a couple, the PDF or printed page return a somewhat correct column width, but not when I attempt the pass all the 25 columns.

Thanks for taking your time to help.

Regards,
Tchapo


 

private void ExportToPDF_Click(object sender, System.Windows.RoutedEventArgs e)
{
    SaveFileDialog dialog = new SaveFileDialog();
    dialog.DefaultExt = "*.pdf";
    dialog.Filter = "Adobe PDF Document (*.pdf)|*.pdf";
 
    if (dialog.ShowDialog() == true)
    {
        RadDocument document = CreateDocument(ReportGridView);
 
        document.LayoutMode = DocumentLayoutMode.Paged;
 
        document.Measure(RadDocument.MAX_DOCUMENT_SIZE);
        document.Arrange(new RectangleF(PointF.Empty, document.DesiredSize));
   
        PdfFormatProvider provider = new PdfFormatProvider();
 
        using (Stream output = dialog.OpenFile())
        {
            provider.Export(document, output);
        }
    }
}
 
private void Print_Click(object sender, System.Windows.RoutedEventArgs e)
{
    Dispatcher.BeginInvoke((Action)(() =>
        {
            RadRichTextBox1.Document = CreateDocument(ReportGridView);
        }));
 
    RadRichTextBox1.Print("MyDocument", Telerik.Windows.Documents.UI.PrintMode.Native);
}
 
private RadDocument CreateDocument(RadGridView grid)
{
    List<GridViewBoundColumnBase> columns = (from c in grid.Columns.OfType<GridViewBoundColumnBase>()
                                                orderby c.DisplayIndex
                                                select c).ToList();
 
    Table table = new Table();
 
    table.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Auto);
    table.LayoutMode = TableLayoutMode.AutoFit;
 
    RadDocument document = new RadDocument();
    document.LayoutMode = DocumentLayoutMode.Paged;
    document.ParagraphDefaultSpacingAfter = document.ParagraphDefaultSpacingBefore = 0;
    document.PageViewMargin = new SizeF(10, 10);
 
 
    Section section = new Section();
    section.Blocks.Add(table);
    document.Sections.Add(section);
 
    if (grid.ShowColumnHeaders)
    {
        TableRow headerRow = new TableRow();
 
        if (grid.GroupDescriptors.Count() > 0)
        {
            TableCell indentCell = new TableCell();
            indentCell.PreferredWidth = new TableWidthUnit(grid.GroupDescriptors.Count() * 20);
            //indentCell.Background = HeaderBackgroundPicker.SelectedColor;
            headerRow.Cells.Add(indentCell);
        }
 
        for (int i = 0; i < columns.Count(); i++)
        {
            TableCell cell = new TableCell();
            //cell.Background = HeaderBackgroundPicker.SelectedColor;
            AddCellValue(cell, columns[i].UniqueName);
            cell.PreferredWidth = new TableWidthUnit((float)columns[i].ActualWidth);
            headerRow.Cells.Add(cell);
        }
 
        table.Rows.Add(headerRow);
    }
 
    if (grid.Items.Groups != null)
    {
        for (int i = 0; i < grid.Items.Groups.Count(); i++)
        {
            AddGroupRow(table, grid.Items.Groups[i] as QueryableCollectionViewGroup, columns, grid);
        }
    }
    else
    {
        AddDataRows(table, grid.Items, columns, grid);
    }
 
    return document;
}
 
private void AddDataRows(Table table, IList items, IList<GridViewBoundColumnBase> columns, RadGridView grid)
{
    for (int i = 0; i < items.Count; i++)
    {
        TableRow row = new TableRow();
 
        if (grid.GroupDescriptors.Count() > 0)
        {
            TableCell indentCell = new TableCell();
            indentCell.PreferredWidth = new TableWidthUnit(grid.GroupDescriptors.Count() * 20);
            //indentCell.Background = RowBackgroundPicker.SelectedColor;
            row.Cells.Add(indentCell);
        }
 
        for (int j = 0; j < columns.Count(); j++)
        {
            TableCell cell = new TableCell();
 
            object value = columns[j].GetValueForItem(items[i]);
 
            AddCellValue(cell, value != null ? value.ToString() : string.Empty);
 
            cell.PreferredWidth = new TableWidthUnit((float)columns[j].ActualWidth);
            //cell.Background = RowBackgroundPicker.SelectedColor;
 
            row.Cells.Add(cell);
        }
 
        table.Rows.Add(row);
    }
}
 
private void AddGroupRow(Table table, QueryableCollectionViewGroup group, IList<GridViewBoundColumnBase> columns, RadGridView grid)
{
    TableRow row = new TableRow();
 
    int level = GetGroupLevel(group);
    if (level > 0)
    {
        TableCell cell = new TableCell();
        cell.PreferredWidth = new TableWidthUnit(level * 20);
        //cell.Background = GroupHeaderBackgroundPicker.SelectedColor;
        row.Cells.Add(cell);
    }
 
    TableCell aggregatesCell = new TableCell();
    //aggregatesCell.Background = GroupHeaderBackgroundPicker.SelectedColor;
    aggregatesCell.ColumnSpan = columns.Count() + (grid.GroupDescriptors.Count() > 0 ? 1 : 0) - (level > 0 ? 1 : 0);
 
    AddCellValue(aggregatesCell, group.Key != null ? group.Key.ToString() : string.Empty);
 
    foreach (AggregateResult result in group.AggregateResults)
    {
        AddCellValue(aggregatesCell, result.FormattedValue != null ? result.FormattedValue.ToString() : string.Empty);
    }
 
    row.Cells.Add(aggregatesCell);
 
    table.Rows.Add(row);
 
    if (group.HasSubgroups)
    {
        for (int i = 0; i < group.Subgroups.Count(); i++)
        {
            AddGroupRow(table, group.Subgroups[i] as QueryableCollectionViewGroup, columns, grid);
        }
    }
    else
    {
        for (int i = 0; i < group.ItemCount; i++)
        {
            AddDataRows(table, group.Items, columns, grid);
        }
    }
}
 
private void AddCellValue(TableCell cell, string value)
{
    try
    {
        Paragraph paragraph = new Paragraph();
        cell.Blocks.Add(paragraph);
 
        Span span = new Span();
        span.Text = value;
 
        paragraph.Inlines.Add(span);
    }
    catch (Exception e)
    {
        string msg = e.Message;
    }
}
 
private int GetGroupLevel(IGroup group)
{
    int level = 0;
 
    IGroup parent = group.ParentGroup;
 
    while (parent != null)
    {
        level++;
        parent = parent.ParentGroup;
    }
 
    return level;
}

 

 

 

 

 

 

 

0
Iva Toteva
Telerik team
answered on 14 Jul 2011, 01:24 PM
Hi Tchapo,

What version of the controls are you using? I tried several versions and was not able to reproduce the exception issue.
With regard to the column width, it cannot be helped that it is small, since there are so much columns in the document. What you can do (if it fits your scenario) is to change the page size and page orientation. This can be done in the following way:

document.DefaultPageLayoutSettings = new PageLayoutSettings(PaperTypes.A2);
document.SectionDefaultPageOrientation = PageOrientation.Landscape;

In order to be able to assist you further, we would need a repro project. If you would like to submit one, you can do so by opening up a support ticket of type "General Feedback" and attaching the project there.

All the best,
Iva
the Telerik team

Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

0
tchapo
Top achievements
Rank 1
answered on 14 Jul 2011, 11:04 PM

Thanks Iva!

Setting document.DefaultPageLayoutSettings = new PageLayoutSettings(PaperTypes.A2); helped a lot. The columns are now of varying width and the text is still wrapped up a little bit, but the overall look is much better. Using A1 instead of A2 gives the best look in pdf but then printed text is too small on regular 8.5x11.
For now it is not bad, but could be better. I may have to submit a sample project depending on the feedback I get from users.


Regards,
Tchapo.

0
F Beto
Top achievements
Rank 1
answered on 12 Jul 2013, 07:42 PM
Hello Iva,

I have a problem with PDF export. My problem is that I have a lot of columns, I mean the amount of RadGridView columns is created dinamically, for example I have the following data:

Column1   Column2   Column3   Column4   Column5   Column6   Column7 ................ ColumnN
data10       data20        data30       data40       data50       data60        data70    ................. dataN0
data11       data21        data31       data41       data51       data61        data71    ................. dataN1
data12       data22        data32       data42       data52       data62        data72    ................. dataN2
data13       data23        data33       data43       data53       data63        data73    ................. dataN3

At this point all the data are being set to the page. It's exporting something like this.

C  C  C ...............................
o   o  o
l    l    l
u  u   u
m m  m
n  n   n
1  2   3


All the data is being exporting in that way. So, I'd like to have this format.

Column1   Column2   Column3    
data10       data20        data30              
data11       data21        data31                            Page1
data12       data22        data32              
data13       data23        data33             

Column4   Column5   Column6
data40       data50       data60
data41       data51       data61                             Page2
data42       data52       data62
data43       data53       data63

Column7 ................ ColumnN
data70    ................. dataN0
data71    ................. dataN1                                 Page3
data72    ................. dataN2
data73    ................. dataN3

Is there any way that can do this operation automatically? do you have any suggestion or examples about this using DadDocument, and PdfFormatProvider?
Please! I need your help!!

Note: I attached the report that was exported with my app.

Thanks in advance!!


0
Petya
Telerik team
answered on 17 Jul 2013, 11:04 AM
Hello,

There are two possible solutions:
  1. Set large PageSIze to the document, so that the generated table has more space.
  2. Modify the logic of the export to "break" the table into several smaller tables. My suggestion is to try measuring the columns of your RadGridView and basically create separate tables from small sets of columns (as demonstrated in your example below). What you should be aware in this regard is that RadDocument's model does not allow consecutive tables, so you should make sure to add at least one empty paragraph between them.

I hope this is helpful!

Regards,
Petya
Telerik
TRY TELERIK'S NEWEST PRODUCT - EQATEC APPLICATION ANALYTICS for WPF.
Learn what features your users use (or don't use) in your application. Know your audience. Target it better. Develop wisely.
Sign up for Free application insights >>
0
F Beto
Top achievements
Rank 1
answered on 17 Jul 2013, 04:45 PM
Thank you for your replay!!!

As you mentioned, my first approach in order to fix this issue was Set large PageSize as you can see in the attached document. So, now I am trying the second approach that is as you mentioned. I'm modifying the logic of the export.

Thank you for your suggestion!!
Tags
General Discussions
Asked by
Matthias
Top achievements
Rank 1
Answers by
Boby
Telerik team
Matthias
Top achievements
Rank 1
Iva Toteva
Telerik team
tchapo
Top achievements
Rank 1
F Beto
Top achievements
Rank 1
Petya
Telerik team
Share this question
or