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:
Set the WrapMode for the
DataGridViewColumn
toDataGridViewTriState.True
Make sure you set a height for the row, or set the DataGridView's
AutoSizeRowsMode
toDataGridViewAutoSizeRowsMode.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.
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.
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.
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)
Is it possible to have Multi-line DataGridView cells without wrapping text?
I hope this is what you are looking for:
I used two events:
- I've measured the height after a cell edit.
- 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;
}
Multiline Textbox to Datagridview
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
If DataGridView1.RowCount = 1 Then DataGridView1.Rows.Clear()
Call dgvstuff()
Timer1.Stop()
End Sub
Sub dgvstuff()
Dim sup2 = TextBox2.Text.Replace("#", "").Replace(">", " "c)
Dim sup() = sup2.Split(" "c, "#", vbCrLf, vbTab)
With DataGridView1
.Rows(0).Cells(0).Value = sup(1).ToString
.Rows(0).Cells(1).Value = sup(7).ToString
.Rows(0).Cells(3).Value = sup(4).ToString
End With
End Sub
I really don't know why but it works like this. Anyone knows a better/cleaner way? Tks
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:
- Cell value fits within the cell width.
- Display normally.
- Cell value is longer than the cell width but shorter than max width.
- Display with ellipses.
- 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;
}
}
This could easily be adapted for multiple columns depending how you set each column's max width.
Multiline Textbox Column in DataGridView
I found the problem. When I set "AutoSizeRowsMode" to "AllCells" that caused the row height to default to what I wanted.
Related Topics
More Elegant Exception Handling Than Multiple Catch Blocks
How to Get the Selected Item of a Combo Box to a String Variable in C#
Regex to Get Src Value from an Img Tag
Getters and Setters Are Bad Oo Design
Application Can't Scaffold Items
String.Format Alternative in C++
How to Display a List of Images, from a Folder on Hard Drive, on ASP.NET Website
C#: Throwing Custom Exception Best Practices
How to Get The Http Post Data in C#
How to Return Dynamic Object from SQL Query
How to Detect Iis Version Using C#
Writing File to Web Server - ASP.NET
How to Convert This C# Rijndael Encryption to PHP