There's nothing you can do about the vertical cutoff problem if the size is variable. If the size is fixed, please adjust it so that this does not happen.
To make the font smaller when the sides are cut off, customize DataGridViewTextBoxColumn as follows:
using System;
using System.Drawing;
using System.Windows.Forms;
public class DataGridViewTextBioxExColumn : DataGridViewTextBoxColumn
{
internal const char CTR_K = '\x0b';
public DataGridViewTextBioxExColumn() {
base.CellTemplate = new DataGridViewTextBioxExCell();
}
}
public class DataGridViewTextBioxExCell : DataGridViewTextBoxCell
{
protected override void OnKeyPress(KeyPressEventArgs e, int rowIndex) {
if (e.KeyChar == DataGridViewTextBioxExColumn.CTR_K) {
Value = string.Empty;
e.Handled = true;
}
base.OnKeyPress(e, rowIndex);
}
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) {
if (rowIndex >= 0 && !DataGridView.Rows[rowIndex].IsNewRow && !IsInEditMode) {
Font prevFont = cellStyle.Font;
string formattedString = formattedValue as string;
Size ms = TextRenderer.MeasureText(graphics, formattedString, prevFont);
const int padding = 4;
int width = cellBounds.Width - padding;
Font newFont = null;
if (ms.Width > width) {
newFont = AdjustFont(graphics, formattedValue as string, width, prevFont);
cellStyle.Font = newFont;
}
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
if (newFont != null) {
cellStyle.Font = prevFont;
newFont.Dispose();
}
} else {
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
static Font AdjustFont(Graphics g, string formattedString, int width, Font font) {
const int carve = 10;
int min = carve;
int max = (int)(font.Size * carve) - 1;
int mid = (min + max) / 2;
while (min + 1 < max) {
using (Font newFont = new Font(font.FontFamily, mid / carve, font.Style)) {
Size ms = TextRenderer.MeasureText(g, formattedString, newFont);
if (ms.Width <= width) {
min = mid;
} else {
max = mid;
}
}
mid = (min + max) / 2;
}
return new Font(font.FontFamily, min / carve, font.Style);
}
public override Type EditType => typeof(DataGridViewTextBoxExEditingControl);
}
public class DataGridViewTextBoxExEditingControl : DataGridViewTextBoxEditingControl
{
protected override void OnKeyPress(KeyPressEventArgs e) {
if (e.KeyChar == DataGridViewTextBioxExColumn.CTR_K) {
Clear();
e.Handled = true;
}
base.OnKeyPress(e);
}
}
![enter image description here](https://learn-attachment.microsoft.com/api/attachments/38aef1f5-690b-4564-8df2-9fef91239d53?platform=QnA)