Skip Navigation LinksHome / Community & Support / Developer Productivity Tools Forums / WPF > General Discussions > Table - adjust column width to content

Not answered Table - adjust column width to content

Feed from this thread
  • Matthias avatar

    Posted on May 4, 2011 (permalink)

    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?

    Reply

  • Boby Boby admin's avatar

    Posted on May 6, 2011 (permalink)

    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

    Reply

  • Say Hello to Telerik's PivotGrid for ASP.NET AJAX, Silverlight, WPF and WinForms. Now packed with OLAP support.
  • Matthias avatar

    Posted on May 6, 2011 (permalink)

    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

    Reply

  • Iva Toteva Iva Toteva admin's avatar

    Posted on May 11, 2011 (permalink)

    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
    Attached files

    Reply

  • Matthias avatar

    Posted on May 12, 2011 (permalink)

    Thanks, that helped much.

    Reply

  • tchapo avatar

    Posted on Jun 23, 2011 (permalink)

    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.

    Reply

  • Boby Boby admin's avatar

    Posted on Jun 30, 2011 (permalink)

    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

    Reply

  • tchapo avatar

    Posted on Jul 11, 2011 (permalink)

    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;
    }

     

     

     

     

     

     

     

    Reply

  • Iva Toteva Iva Toteva admin's avatar

    Posted on Jul 14, 2011 (permalink)

    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!

    Reply

  • tchapo avatar

    Posted on Jul 14, 2011 (permalink)

    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.

    Reply

  • Say Hello to Telerik's PivotGrid for ASP.NET AJAX, Silverlight, WPF and WinForms. Now packed with OLAP support.

Back to Top

Skip Navigation LinksHome / Community & Support / Developer Productivity Tools Forums / WPF > General Discussions > Table - adjust column width to content