We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Setting column width to show certain number of characters...

Hi,

I am using 4.4.x.x GDBG
I know that you can calculate the preferred column width and resize to content and all that. But I have a different case.

I want to be able to set the width of the column so that it displays exactly, let's say, 100 characters ( Actual cell value is immaterial. It could be more than 100 or less than 100 characters.)

Is there a way to calculate the width of the column based on that information?


Thanks,
Pratima
For ex.

2 Replies

AD Administrator Syncfusion Team June 9, 2007 01:04 AM UTC

If the font you choose to use has the property that all characters have the same width, then you can do it. But if you use one of the more common non-monospaced fonts, then it is a problem. With such fonts, 100 W's will be much wider than 100 i's.

You can use Graphics.MeasureString to get the size of a particular string using a particular font. Once you have your target width, then you can use grid.Model.ColsWidths collection to set the width of a column.


RA Rajagopal Syncfusion Team June 9, 2007 01:54 AM UTC

Hi Pratima,

By default grid uses .Net graphics MeasureString method to calculate the size of the string. When the ResizeToFit method is called, Grid calls the CellModel.OnQueryPreferredClientSize which internally calls this method. You can use the code below to calculate the width of the characters inside any particular cell.

private int CalculateWidth(int row, int column)
{
GridStyleInfo style = gridDataBoundGrid.Model[row, column];
using (Graphics g = CreateGraphics())
{
string text = style.Text;
float width = g.MeasureString(text, style.GdipFont).Width;
int calculatedWidth = Convert.ToInt32(width);

return calculatedWidth;
}
}

Let us know if you need any further information.
Regards,
Rajagopal

Loader.
Live Chat Icon For mobile
Up arrow icon