Multi-line cells in DataGridView?

Yuliya

Active member
Joined
Nov 9, 2007
Messages
34
Programming Experience
Beginner
Is it possible to have multi-line cells in a DataGridView? Thank you!
 
Yes, but not by default. You can embed any control you like in any DataGridViewCell but there are only certain embedded controls available by default and they only expose certain of their properties. Your two main options are:

1. Handle the EditingControlShowing event of your grid and, if it is in the appropriate column, get a reference to the TextBox that is the EditingControl and set its MultiLine property to True.

2. Inherit the DataGridViewTextBoxColumn and DataGridViewTextBoxCell classes and propagate the MultiLine property of the cell's embedded control up through the cell and column so you can set it at the column level.

The second option is more complex but will produce a better result. You can also implement functionality to display the TextBox at a larger size while editing to display more of the text. If you're inexperienced, though, you might like to stick with the first option for now. You won't actually see multiple lines unless you make the rows taller though.
 
Set WrapMode=True for the textbox column and adjust the row height, see for example this post.
 
The best way is by handling the EditingControlShowing event of the grid and add the following code:

If TypeOf e.Control Is TextBox Then
Dim txtB As TextBox = New TextBox
txtB = e.Control
txtB .Multiline = True
txtB .ScrollBars = ScrollBars.Both
End If

Also, set the property WrapMode=True for the columns DefaultsCellStyle.
Remember to press Shift+Enter for linefeed.
In this way you will get a multi line textbox for every TextBoxCell. If you want to set the multiline for only one column, you have to check, in If clause, if it is the appropriate column which is being edit
 
That code for Multiline is not necessary olcinium. When you set WrapMode to True the TextBox editing control gets Multiline property set automatically.
Also, why do you create a new TextBox control each time editing control is showing ? This is a mistake.
 
yes, but in this way it behaves much better, especially when you get the scroll bars on the cell.
I used to do only withe the WrapMode, but not any more.
 
fixed code:
VB.NET:
If TypeOf e.Control Is TextBox Then
     CType(e.Control, TextBox).ScrollBars = ScrollBars.Both
End If
 
That fix is not about elegancy, it is about fixing the memory leak you introduced and removing the redundant call to Multiline property. If you need to do more with the editing control you would use a variable for easier reference like this:
VB.NET:
Dim tb As TextBox = CType(e.Control, TextBox)
Notice this code does not create and throw away a New TextBox.
 
Back
Top