TL;DR
It seems the only piece I'm missing now is how to find the preferred width of a cell as it's being created. I need a replacement for Graphics.MeasureString
that works for web forms.
ORIGINAL POST
I'm trying to set up a web page that will have a programmatically built dynamic table on it displaying some numeric data. This table will have multiple columns. The left-most column will have a label telling the user what the data in that particular row is for. The rest of the columns in that row will contain various numeric data.
What I'm trying to do is have two different widths for the cells. The width for the left-most column should be wide enough to fit the longest label in all the rows of the table. The width of all the other columns should be wide enough to fit the longest string in any of the data columns in any row. So in the simple sample below, COLUMN A
is going to be wide enough to fit a really really long label
. COLUMN B
, COLUMN C
, and COLUMN D
all need to be the same width, and wide enough to hold 123456789
.
I feel like I should be using styles for this, but I'm not quite sure how to implement it. Can I just assign one style to each of the COLUMN A
cells as they are created, then actually specify what the width of that style is after I've created all the rows (and then apply a second style to all the COLUMN B
, COLUMN C
, and COLUMN D
cells)? Will I need to find and record the max width for each style myself, or will the framework take care of that for me (the same way the width of a normal label is automatically set to be as wide as is needed to display it's contents)? If I need to find and record it myself, how do I do that? I found stuff about TextRenderer.MeasureText and Graphics.MeasureString, and several others like them, but they seem to only apply to Windows Application projects, not to Web projects.
UPDATE 1
Buried near the end of the MSDN page I found this note:
Each time one of the Style property values changes, each control must call its ApplyStyle method.
So that addresses one of my questions - When I'm creating each of my cells, I'll have to record the widest style. Once all the cells are created, I need to set the width
property of my styles to the largest width I recorded. Lastly, I'll need to loop over all my cells again and call applyStyle
on each of them again.
UPDATE 2
I was able to implement the code I mentioned in my last update, and it all seems to work as I had hoped it would. I still am not able to find a way to get the preferred width of a cell/label/string. As a temporary solution, I have simply hard-coded the width to a value that is suitable for now just before re-applying the styles, but since I want this table to be very dynamic, I would still prefer to not have to hard-code a value, so I am still looking for a way to get that preferred width.