Although @Zach Johnson answered the bulk of this question, its code did not work for me. After spending a long time and reading various topics, I realized that you also need to set some properties in order to get this working. So, here is the full code, so you can run the example: Define CustomDataGridViewTextBoxCell:
class CustomDataGridViewTextBoxCell: DataGridViewTextBoxCell { public override Type EditType => typeof(CustomDataGridViewTextBoxEditingControl); }
Then define the CustomDataGridViewTextBoxEditingControl class
class CustomDataGridViewTextBoxEditingControl : DataGridViewTextBoxEditingControl { public override bool EditingControlWantsInputKey( Keys keyData, bool dataGridViewWantsInputKey) { switch (keyData & Keys.KeyCode) { case Keys.Enter:
Then define the DataGridViewRolloverCell :
public class DataGridViewRolloverCell : DataGridViewTextBoxCell { public override Type EditType => typeof(CustomDataGridViewTextBoxEditingControl); }
After that, we define the DataGridViewCustomColumn class:
public class DataGridViewCustomColumn : DataGridViewColumn { public DataGridViewCustomColumn() { this.CellTemplate = new CustomDataGridViewTextBoxCell(); } }
Now, if you have a DatagridViewControl called dgv , your code will look like this:
DataGridViewCustomColumn col = new DataGridViewCustomColumn(); dgv.Columns.Add(col);
Now itβs important : you should still set the WrapText property to DefaultCellStyle to true . Do this in the constructor or with this code:
DataGridViewCellStyle dataGridViewCellStyle1 = DataGridViewCellStyle(); dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dgv.DefaultCellStyle = dataGridViewCellStyle1;
And don't forget to set the Datagridview.AutoSizeRowsMode property in AllCells . Then it will work.
Code pope
source share