I have an unbound DataGridView (in VS 2008), of which one column contains a file path. I'd like to format the string using the TextRenderer class on the ColumnWidthChanged event without actually modifying the underlying value. The problem is that the contents of the table are saved when the form is closed and I don't want to save the formatted value. I think I'm just in too deep to see the obvious solution so I'm depending on you guys to point it out :-).
The idea is to display this:
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe
...as this (depending on the width of the column):
C:\Program Files\Microso…\gacutil.exe
It appears I spoke too soon. I'm getting some very strange results from TextRenderer.MeasureText(). If I hardcode the path value as "C:\Documents and Settings\jluce\My Documents\Downloads" it comes ends up as C:\Documents and Settings\jluce\M...\Downloads\0wnloads". If I don't hardcode it (like below) it gets further corrupted each time I resize the column.
Here's what it looks like after a couple resizes: Screenshot
Here's what I'm currently doing.
if (e.ColumnIndex == 1)
{
foreach (DataGridViewRow Row in mappingsDataGrid.Rows)
{
string Path = (string)Row.Cells[1].Value;
Path = Path.Trim();
TextRenderer.MeasureText(Path, e.CellStyle.Font,
new Size(mappingsDataGrid.Columns[e.ColumnIndex].Width, Row.Height),
TextFormatFlags.ModifyString | TextFormatFlags.PathEllipsis);
e.Value = Path;
}
}
This just keeps getting weirder!!
I managed to fix the problem of the mangled string by iterating through each char and removing the bad ones. However, now I've got an even crazier problem. A local variable I'm assigning in the event handler is retaining its value between calls.
Here's the relevant code:
string Path = ""; // <-- #1
Path = "C:\\Documents and Settings\\jluce\\My Documents\\Downloads"; // <-- #2
TextRenderer.MeasureText(Path, Row.Cells[1].Style.Font,
new Size((mappingsDataGrid.Columns[e.Column.Index].Width), Row.Height),
TextFormatFlags.ModifyString | TextFormatFlags.PathEllipsis);
// Left out code that strips invalid chars
Row.Cells[1].Value = Path; // <-- #3
Path = null;
First time resizing column (refer to #'s in the comments above):
- After this line Path contains "".
- After this line Path contains string just as it appears above.
- Path contains truncated file path as it should (i.e. "C:\Documents and Setti...\Downloads")
Second time resizing:
- After this line Path contains "", as it should.
- After this line Path contains "C:\Documents and Set...\Downloads\0 Documents\Downloads", which was the invalid value from the previous iteration before I stripped out the invalid characters (seen here as '\0')!!
- Now the path is FUBAR because I started with a screwed up string and it just keeps getting worse.
Why would Path be assigned the invalid value from the previous function call (after correctly assigning an empty string!) when I'm explicitly assigning a value to it?!!!!!