如何使DataGridView的宽度和高度适合其内容? [英] How to fit DataGridView width and height to its content?

查看:76
本文介绍了如何使DataGridView的宽度和高度适合其内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种动态创建DataGridView的方法,但是当它显示时,其宽度大于内容宽度(列的总宽度)。而且,高度的长度不足以满足行的长度。

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.

我尝试使用此方法,但没有用:

    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);
        }
    }

结果:

您可以看到DataGridView控件的宽度很长我怎样才能适合两个维度?

As you can see the width of the DataGridView control is so long. How can I fit it for both dimension?

推荐答案

主要问题是您新创建的 DataGridView 在添加到父容器之前尚未完成其内部布局,并且仍将报告所有列的宽度为100。

The main problem is that your newly created DataGridView has not finished its internal layout before being added to a parent container and will still report all columns as having a width = 100.

修复了在显示DGV之后 调用大小调整功能的问题:

One way to fix it is to call a sizing function after the DGV has been displayed:

void sizeDGV(DataGridView dgv)
{
    DataGridViewElementStates states = DataGridViewElementStates.None;
    dgv.ScrollBars = ScrollBars.None;
    var totalHeight = dgv.Rows.GetRowsHeight(states) + dgv.ColumnHeadersHeight;
    totalHeight += dgv.Rows.Count * 4  // a correction I need
    var totalWidth = dgv.Columns.GetColumnsWidth(states) + dgv.RowHeadersWidth;
    dgv.ClientSize = new Size(totalWidth , totalHeight );
}

请注意,我已经解决了一些问题:

Note that I have fixed a few things along the way:


  • 宽度和高度都没有包括标题

  • 更改外部尺寸将忽略边框。我改为更改ClientSize。

  • 在大小可用之前,我们需要关闭滚动条。

这篇关于如何使DataGridView的宽度和高度适合其内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆