I have already set the DataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True
But this WrapMode
does not wrap columns with single word without spaces. Is there any way we can "break-word" along with WrapMode
? Or any other solution?
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
, ie 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..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.