I have a method to create DataGridView dynamically but when it is shown up, the width is greater than the content width (total width of the columns). Also the height has not enough length to meet the length of the rows.
I tried using this method but it didn't work:
DataGridView CreateInputBox(int proc, int mac)
{
DataGridView databox = new DataGridView();
for (int i = 0; i < mac; i++)
{
databox.Columns.Add("col" + (i + 1), "M" + (i + 1));
databox.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
databox.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
databox.RowTemplate.DefaultHeaderCellType = typeof(CustomHeaderCell);
databox.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
databox.RowHeadersDefaultCellStyle.Padding = new Padding(2);
for (int i = 0; i < proc; i++)
{
databox.Rows.Add();
databox.Rows[i].HeaderCell.Value = "P" + (i + 1);
}
databox.DefaultCellStyle.SelectionBackColor = Color.LightGray;
databox.AllowUserToAddRows = false;
databox.AllowUserToDeleteRows = false;
databox.AllowUserToOrderColumns = false;
databox.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
databox.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
//This block doesn't work
var totalHeight = databox.Rows.GetRowsHeight(DataGridViewElementStates.None);
var totalWidth = databox.Columns.GetColumnsWidth(DataGridViewElementStates.None);
databox.Width = totalWidth;
databox.Height = totalHeight;
//
return databox;
}
public class CustomHeaderCell : DataGridViewRowHeaderCell
{
protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
{
var size1 = base.GetPreferredSize(graphics, cellStyle, rowIndex, constraintSize);
var value = string.Format("{0}", this.DataGridView.Rows[rowIndex].HeaderCell.FormattedValue);
var size2 = TextRenderer.MeasureText(value, cellStyle.Font);
var padding = cellStyle.Padding;
return new Size(size2.Width + padding.Left + padding.Right, size1.Height);
}
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)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, DataGridViewPaintParts.Background);
base.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
TextRenderer.DrawText(graphics, string.Format("{0}", formattedValue), cellStyle.Font, cellBounds, cellStyle.ForeColor);
}
}
Result:
As you can see the width of the DataGridView control is so long. How can I fit it for both dimension?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…