【发布时间】:2014-03-21 20:50:10
【问题描述】:
我正在以编程方式构建一个 DataGridView 表并将其放置在表单上的 GroupBox 中。
我插入数据,然后自动调整列大小以适应数据。然后我想将 groupbox 的大小调整为 DataGridView 的大小。对于每一列和每一行,我得到它们各自的宽度和高度,这在技术上应该是准确的,并更新面板和整体 DataGridView 大小。
问题是 Column.Width 总是返回 100 像素,无论其实际大小如何(见截图:实际列宽约为 30 像素,而不是 100)。如果我手动输入宽度 = 90 像素,则调整大小非常准确!
matrix = new DataGridView();
//modify behaviour
matrix.ColumnHeadersVisible = false;
matrix.AllowUserToResizeColumns = false;
matrix.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
matrix.RowHeadersVisible = false;
matrix.AllowUserToResizeRows = false;
//modify positioning
matrix.Location = new Point(10, 20);
//matrix.Anchor = (AnchorStyles)(AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right);
matrix.Dock = DockStyle.Fill;
//set the size of the matrix
matrix.ColumnCount = col;
matrix.RowCount = row;
//Data now inserted...
matrix.AutoResizeColumns(); //correctly resizes the columns
int height = 0;
foreach (DataGridViewRow row in matrix.Rows)
{
height += row.Height;
}
height += matrix.ColumnHeadersHeight;
int width = 0;
foreach (DataGridViewColumn col in matrix.Columns)
{
width += col.Width;
//PROBLEM: Width always = 100 pixels.
}
width += matrix.RowHeadersWidth;
//width = 90; //override width manually
matrix.Size = new Size(width + 2, height + 2);
panel.Size = new Size(matrix.Width, matrix.Height);
面板这么大是因为宽度不是 90px 而是大约 357,这是错误的!
编辑:部分修复 我找到了一种方法来获得正确的单元格宽度:
DataGridView.Rows[0].Cells[0].ContentBounds.Width
//ContentBounds = a rectangle with the exact dimensions of that cell
我现在可以将 DataGridView 设置为正确的大小,但前提是它没有停靠到填充。设置 matrix.Dock = DockStyle.Fill 会阻止正确调整大小。
【问题讨论】:
标签: c# datagridview