4

I am trying to display text in multiple lines in a DataGridView Cell. I don't want to use the Wrap mode because the text is not very lengthy. I just want to show the first word on the first line and the second one on the next something like this. Note the bold text on second line.


Name: abc
City: xyz

I tried doing it using Environment.NewLine and "\r\n" but neither works.

private void dgv_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow dgvrow in dgv.Rows)
        {  
            if (dgv.CurrentCell.ColumnIndex == dgv.Columns["Name"].Index)
            {
                DataGridViewCell dgvcell = (DataGridViewCell)dgvrow.Cells["Name"];
                string Name = dgvcell.Value.ToString();
                string City = Name.Substring(Name.IndexOf("City:"));
                Name = Name.Substring(0, Name.IndexOf("City:")) + Environment.NewLine + City;
                dgvcell.Value = Name;
            }
        }
    }

Can anyone suggest how this can be achieved? Thanks.

user3007740
  • 91
  • 1
  • 2
  • 9

5 Answers5

4

You should be able to achieve this by setting the WrapMode of the DefaultCellStyle of your DataGridViewTextBoxColumn to true, and setting AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells.

Marton
  • 813
  • 7
  • 18
  • 2
    The words on both the lines can have spaces in between. In such cases, the text gets wrapped at the space rather than at the newline. I need a way to wrap the text exactly at the newline. – user3007740 Dec 13 '13 at 10:28
1

This works for me:

dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True; 
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells; 
Wolfgang Schorge
  • 157
  • 1
  • 10
0

Try this.. You need to set AutoSizeColumnsMode to AllCells.

        foreach (DataGridViewRow dgvrow in dgv.Rows)
        {
            if (dgv.CurrentCell.ColumnIndex == dgv.Columns["Name"].Index)
            {
                DataGridViewCell dgvcell = (DataGridViewCell)dgvrow.Cells["Name"];
                string Name = dgvcell.Value.ToString();
                string City = Name.Substring(Name.IndexOf("City:"));
                Name = Name+"\r\n"+City;
                dgvcell.Value = Name;
            }
        }

It will work for sure

Learner
  • 1,286
  • 6
  • 34
  • 57
  • It still doesn't work. Some rows get wrapped at space and some others at newline depending on the word length. Ideally what I want is to have everything before the newline in a single line whatever the word length is. And the same with text after the newline. Thanks. – user3007740 Dec 13 '13 at 12:18
  • then do one thing, In the cellvalidating take the whole cell value and split them into words to a string array. And join all the words with "\r\n" and set the whole string to same cell. It works – Learner Dec 16 '13 at 08:40
0

I had a similar difficulty, in that I wanted to use wrapping, but only where I specified it to be wrapped with a newline character. My solution was to resize the column width based upon the longest string I didn't want wrapped, and then let the wrapping do the rest.

Feel free to try the following, or modify it to suit your purposes.

private void dataGridView_TextItems_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (sender is DataGridView dgv && dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewTextBoxCell cell)
        {
            SetDGVTextBoxColumnWidth(dgv.Columns[e.ColumnIndex] as DataGridViewTextBoxColumn);
        }
    }

    private void SetDGVTextBoxColumnWidth(DataGridViewTextBoxColumn column)
    {
        if (column != null)
        {
            DataGridView dgv = column.DataGridView;
            Graphics g = dgv.CreateGraphics();
            Font font = dgv.Font;

            // Acquire all the relevant cells - the whole column's collection of cells:
            List<DataGridViewTextBoxCell> cells = new List<DataGridViewTextBoxCell>();
            foreach (DataGridViewRow row in column.DataGridView.Rows)
            {
                cells.Add(row.Cells[column.Index] as DataGridViewTextBoxCell);
            }

            // Now find the widest cell:
            int widestCellWidth = g.MeasureString(column.HeaderText, font).ToSize().Width;  // Start with the header text, but for some reason this seems a bit short.
            bool foundNewline = false;
            foreach (DataGridViewTextBoxCell cell in cells)
            {
                font = ((cell.Style.Font != null) ? cell.Style.Font : dgv.Font);  // The font may change between cells.
                string cellText = cell.Value.ToString().Replace("\r","");  // Ignore any carriage return characters.  
                if (cellText.Contains('\n'))
                {
                    foundNewline = true;
                    cell.Style.WrapMode = DataGridViewTriState.True;  // This allows newlines in the cell's text to be recognised.

                    string[] lines = cellText.Split('\n');
                    foreach (string line in lines)
                    {
                        int textWidth = g.MeasureString(line + "_", font).ToSize().Width;  // A simple way to ensure that there is room for this text.
                        widestCellWidth = Math.Max(widestCellWidth, textWidth);
                    }
                }
                else
                {
                    int textWidth = g.MeasureString(cellText + "_", font).ToSize().Width;
                    widestCellWidth = Math.Max(widestCellWidth, textWidth);
                }
            }
            if (foundNewline)
            {
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;  // Allows us to programatically modify the column width.
                column.Width = widestCellWidth;  // Simply set the desired width.
            }
            else
            {
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;  // Allow the system to do the work for us.  This does a better job with cell headers.
            }
            column.Resizable = DataGridViewTriState.False;  // We don't wish the User to modify the width of this column manually.
        }
    }
bertie
  • 11
  • 2
-1

I fixed it by handling the DataGridView_CellFormatting event and formatting the text as required. Thanks everyone for your suggestions.

user3007740
  • 91
  • 1
  • 2
  • 9