Click here to Skip to main content
15,668,691 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I had set the WrapMode = true, but it does not wrap the text that without spaces and I try to play with the CellPainting Event, but it still did not show the whole sentences in the datagridview. I want to make it larger each time when it is necessary.

Please have a look on the image to have better understanding on the current situation. Here's the link: SCREENSHOT1[^]

What I have tried:

dataGridView3.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView3.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

private void dataGridView3_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();

    e.PaintBackground(e.CellBounds, selected);
    e.Graphics.DrawString(s, dataGridView1.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;

Updated 17-Mar-22 23:56pm

1 solution

You could use the TextRenderer.MeasureText Method[^]
to create a routine that wraps the text in a given box size.

Also see: TextFormatFlags Enum[^]

And this might be useful too: visual studio - C# - DataGridView with Wrap text in Cell but without spaces - Stack Overflow[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900