C#: Multiline Text in Datagridview Control

C#: multiline text in DataGridView control

You should set DefaultCellStyle.WrapMode property of column to DataGridViewTriState.True. After that text in cells will be displayed correctly.

Example (DataGridView with one column):

dataGridView1.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.Rows.Add("test" + Environment.NewLine + "test");

(Environment.NewLine = \r\n in Windows)

Multiline text in DataGridView Cell

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

How to set DataGridView textbox column to multi-line?

You should be able to achieve this by setting the WrapMode of the DefaultCellStyle of your DataGridViewTextBoxColumn to true.

Multiple lines in a DataGridView cell

I don't know if this will satisfy you, but you can use Environment.NewLine to create simple line break inside cell.

Example:

string nl = Environment.NewLine; // new line variable
string data = "1 2 3" + nl + "4 5 6" + nl + "7 8 9";

Added later:

As Adrian said in comments - you will need to:

  1. Set the WrapMode for the DataGridViewColumn to DataGridViewTriState.True

  2. Make sure you set a height for the row, or set the DataGridView's AutoSizeRowsMode to DataGridViewAutoSizeRowsMode.AllCells

If you don't want to edit that column - you can set DataGridView.Column.ReadOnly property to true.

Update:
It took me a while to find this property with the above information. In VS C# 2017 the WrapMode property is located in the datagridview DefaultCellStyle dialog.

Datagridview multi line textbox when ctrl+enter press

I am fairly confident you can achieve the desired results by changing a couple of properties in the DataGridView and use a “Shift-Enter” instead of “Ctrl-Enter”.

In the DataGridView set its AutoSizeRowsMode to AllCells, then set the particular COLUMNS DefaultCellStyle -> WrapMode to true. Then use a “Shift-Enter” while editing a cell and you should get multiple lines in a cell. Hope this is what you were looking for.

Is it possible to have Multi-line DataGridView cells without wrapping text?

I hope this is what you are looking for:
Screen shot

I used two events:

  1. I've measured the height after a cell edit.
  2. I've measured text when painting cell, and trimmed it if needed, and repeat till it fits.

Code:

public partial class Form1 : Form
{
private readonly int _rowMargins;

public Form1()
{
InitializeComponent();
int rowHeight = dataGridView1.Rows[0].Height;
_rowMargins = rowHeight - dataGridView1.Font.Height;
}

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridView view = sender as DataGridView;
DataGridViewCell cell = view.Rows[e.RowIndex].Cells[e.ColumnIndex];
string text = string.Format("{0}", cell.FormattedValue);
if (!string.IsNullOrEmpty(text))
{
Size size = TextRenderer.MeasureText(text, view.Font);
view.Rows[e.RowIndex].Height = Math.Max(size.Height + _rowMargins, view.Rows[e.RowIndex].Height);
}
}

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == -1 || e.RowIndex == -1)
{
return;
}
e.Paint(e.ClipBounds, DataGridViewPaintParts.All ^ DataGridViewPaintParts.ContentForeground);

DataGridView view = sender as DataGridView;

string textToDisplay = TrimTextToFit(string.Format("{0}", e.FormattedValue), (int) (e.CellBounds.Width * 0.96), view.Font);

bool selected = view.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
SolidBrush brush = new SolidBrush(selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);

e.Graphics.DrawString(textToDisplay, view.Font, brush, e.CellBounds.X, e.CellBounds.Y + _rowMargins / 2);

e.Handled = true;
}

private static string TrimTextToFit(string text, int contentWidth, Font font)
{
Size size = TextRenderer.MeasureText(text, font);

if (size.Width < contentWidth)
{
return text;
}

int i = 0;
StringBuilder sb = new StringBuilder();
while (i < text.Length)
{
sb.Append(text[i++]);
size = TextRenderer.MeasureText(sb.ToString(), font);

if (size.Width <= contentWidth) continue;

sb.Append("...");

while (sb.Length > 3 && size.Width > contentWidth)
{
sb.Remove(sb.Length - 4, 1);
size = TextRenderer.MeasureText(sb.ToString(), font);
}

while (i < text.Length && text[i] != Environment.NewLine[0])
{
i++;
}
}
return sb.ToString();
}

}

Enjoy,

Ofir

Designer code:

partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.LineNumber = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Content = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.LineNumber,
this.Content});
this.dataGridView1.Location = new System.Drawing.Point(13, 13);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersWidth = 55;
this.dataGridView1.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridView1.Size = new System.Drawing.Size(493, 237);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit);
this.dataGridView1.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);
//
// LineNumber
//
this.LineNumber.FillWeight = 30F;
this.LineNumber.Frozen = true;
this.LineNumber.HeaderText = "#";
this.LineNumber.MaxInputLength = 3;
this.LineNumber.Name = "LineNumber";
this.LineNumber.ReadOnly = true;
this.LineNumber.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.LineNumber.Width = 30;
//
// Content
//
this.Content.HeaderText = "Content";
this.Content.Name = "Content";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(518, 262);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Is it possible to have Multi-line DataGridView cells without wrapping text?";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.DataGridViewTextBoxColumn LineNumber;
private System.Windows.Forms.DataGridViewTextBoxColumn Content;
}

Change datagrid view cell to multiline if its content gets more than a specific width

I'm not sure how you are setting a column's maximum width. But if that maximum width is equivalent to the column's actual width, then the answer is simply:

dataGridView1.Columns[columnIndex].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.AutoResizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

As explained here, here, and numerous other places.

If they are not equivalent then you could have the following situations:

  1. Cell value fits within the cell width.

    • Display normally.
  2. Cell value is longer than the cell width but shorter than max width.

    • Display with ellipses.
  3. Cell value is longer than the cell width and the max width.

    • Display as a multiline/wrapped cell.

To handle it is pretty similar but on a cell by cell basis instead of the whole column. Below is an example:

private int column0MaxWidth = 100;
this.dataGridView1.Columns[0].Width = 55;
this.dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

// For contrast - column 1 contains the same data but is autosized.
this.dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

// On cell formatting, change a cell to single-lined or multilined.
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewTextBoxCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewTextBoxCell;

if (cell != null && e.ColumnIndex == 0)
{
cell.Style.WrapMode = TextRenderer.MeasureText(cell.Value.ToString(), cell.Style.Font).Width > column0MaxWidth ? DataGridViewTriState.True : DataGridViewTriState.NotSet;
}
}

Wrapped vs unwrapped cell

This could easily be adapted for multiple columns depending how you set each column's max width.

How can I display multi line text from access database into DataGridView in C#

Do this in your DataBase

Sample Image

And Add this query to display data from MS-Access into dataGridView without (<div>) annoying tag

 
OleDbConnection con = new OleDbConnection("your connection string");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand();

private void getDataBtn_Click(object sender, EventArgs e)
{
cmd.Connection = con;
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [Table]", con);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}

How to achieve multi line header in DataGridView using property grid?

So I used Environment.NewLine in the designer.cs where the header text was assigned. Though the property grid shows just a string with no newline characters, while the GridView renders, the header text was coming in multiple lines as expected.



Related Topics



Leave a reply



Submit