I have a multi-line DataGridView, how would you find where the word wrap takes place in the string Cell.Value
?
-
Read http://stackoverflow.com/faq – nawfal Feb 22 '13 at 14:24
-
Depends on your Column-Width: http://msdn.microsoft.com/de-de/library/system.windows.forms.datagridviewcolumn.width.aspx – jAC Feb 22 '13 at 14:24
2 Answers
string testLength = "1";
private void DataSheets_Load(object sender, EventArgs e) //DataGridView, 2 columns
{
clmData.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
Data.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
Data.DefaultCellStyle.Font = new Font("Courier", 8);
RunWidth();
}
void RunWidth()
{
int l1 = len(testLength);
int l2 = len(testLength + testLength);
int perChar = l2 - l1;
int pad = l1 - perChar;
int s7 = pad + (perChar * 75);
int s5 = pad + (perChar * 50);
Data.Columns[0].Width = s7;
Data.Columns[1].Width = s5;
}
public int len(string text)
{
Size te = TextRenderer.MeasureText(text, new Font("Courier", 8));
return te.Width;
}
I solved it on my own, but if someone finds more ways to find a similar function applicable please continue posting results.

- 273
- 3
- 4
- 20
Just because it has a lot of good info:
Here's a very well elaborated answer on differences between TextRenderer.MeasureText()
and Graphics.MeasureString()
I had a similiar problem; I wanted to know how many lines are created by wrapping when drawing a DataGridViewRow
by myself (code is C++/CLI):
void PaintRow (Object^ sender, DataGridViewRowPrePaintEventArgs^ e)
{
...
int iCharacters = 0, iLines = 0;
SizeF oLayoutArea ((float)dgvRow->Cells[ixCell]->Size.Width, 0);
SizeF oTextSize = e->Graphics->MeasureString (sText,
dgvRow->Cells[ixCell]->InheritedStyle->Font,
oLayoutArea,
oStringFormat,
iCharacters,
iLines);
On your question:
I would take the same code and find out how many lines are created by the full string, e.g. 2 lines.
Then take half of the string, and check out how many lines you get, e.g. 1 line.
Because it is less lines that before, I would take more text again (always half of the difference) and test once more.
Continue until you have broken it down to one character and got your resulting length that fits without wrapping.

- 3,361
- 1
- 21
- 45