Reputation: 49
How can we wrap text without spaces in DataGridView?
I set DataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True
.
But WrapMode
does not wrap columns with a single word without spaces.
How can we word break along with WrapMode
?
Upvotes: 4
Views: 6444
Reputation: 2206
Simply add the following line after DataBinding:
DGLogs.Columns[0].DefaultCellStyle.WrapMode=DataGridViewTriState.True;
set
AutosizecolumnMode=AllCells
AutosizeRowMode=AllCells
in Property windows
The output will be as shown in the below image:
Upvotes: 2
Reputation: 54453
You can play with the CellPainting
event.
The DrawString
respects the bounding Rectangle
and wraps wherever it hits the right boundary.
You can uncomment the condition to apply only to cells which go over a limit you set.
For best control you would have to measure the length of the FormattedValue
to find out the exact limit.
You may also want to fine-tune the draw position, if you have special alignments in your cells.
private void DGV1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.Value == null) return;
if (e.FormattedValue.GetType() != typeof( System.String) ) return;
bool selected = (e.State & DataGridViewElementStates.Selected)
== DataGridViewElementStates.Selected;
string s = e.FormattedValue.ToString();
//if (s.Length > 20) // Apply to all or only those breaking your limits
{
e.PaintBackground(e.CellBounds, selected);
e.Graphics.DrawString(s, DGV1.Font, selected ?
SystemBrushes.HighlightText : SystemBrushes.ControlText,
new Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 2,
e.CellBounds.Width - 2, e.CellBounds.Height - 4));
e.Handled = true;
}
}
Setting the Row.Heights
is up to you. If you go for measuring the FormattedValue
you will get a RectangleF
back; so you'll also know the necessary Height
for that Cell
. Comparing it to the current Row.Height
you could gradually adapt it for each Row
, i.e. make it larger each time it is necessary.. I didn't include, because it will result in Rows with varying Heights and that may be unwanted/unnecessary in your case. If you're interested, I can post the code, though..
Upvotes: 3