.net 数据网格视图自动调整大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6424514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:40:03  来源:igfitidea点击:

DataGridView AutoSize

.netwinforms

提问by SiberianGuy

Is there any way to make DataGridView fit the width and height of colums/rows? I have found the solution which requires manual calulation: http://www.codeguru.com/csharp/.net/net_data/datagrid/article.php/c9603Does DataGridView really not support this feature?

有没有办法让 DataGridView 适合列/行的宽度和高度?我找到了需要手动计算的解决方案:http: //www.codeguru.com/csharp/.net/net_data/datagrid/article.php/c9603DataGridView 真的不支持这个功能吗?

回答by love Computer science

if you want to make all the columns to resize automatically according to data:

如果您想让所有列根据数据自动调整大小:

for (int i = 0; i < dataGridView.Columns.Count; i++)
{
    dataGridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}

回答by Larry

This is a pretty old question that has been misunderstood IMHO. What Idsa wants to achieve is to make the actual AutoSizewinforms feature to work with the DataGridView. The property exists but it has no effect.

这是一个很老的问题,恕我直言被误解了。Idsa 想要实现的是使实际的AutoSizewinforms 功能与 DataGridView 一起使用。该属性存在但没有效果。

This means the DataGridView has to fit aroundits content, not its content has to fit insidethe DataGridView.

这意味着在DataGridView必须适应周围的内容,而不是它的内容,以适应内部DataGridView的。

There are a lot of things to think about to achieve a AutoSize implementation. The DataGridView size depends on a lot of criterias:

要实现 AutoSize 实现,需要考虑很多事情。DataGridView 的大小取决于很多标准:

  • Border size
  • Padding
  • Cell Delimiter size
  • Row Header height
  • Column header width
  • How the DataGridView is populated (DataBound or manually)
  • ... a lot more
  • 边框尺寸
  • 填充
  • 单元格定界符大小
  • 行标题高度
  • 列标题宽度
  • 如何填充 DataGridView(DataBound 或手动)
  • ... 多很多

The best is to select a set of some criteria that fits your specific scenario, and write something that will compute the DataGridView size for you.

最好的方法是选择一组适合您特定场景的标准,并编写一些内容来为您计算 DataGridView 大小。

Here my specific scenario as an example:

这里以我的具体场景为例:

  • my grid is data bound. So its size is supposed to change each time a DataBinding operation is complete. This is the condition that trigger a recalculation of the DataGridView size. So I hook it to the DataBindingCompleteevent.

  • my grid is not supposed to display scrollbars. So I set the Scrollbarsproperty to None.

  • My row and columns autosize mode are set to AllCells.

  • Rows and Columns header are not visible. If they were, their sizes has to be included in the calculation.

  • 我的网格是数据绑定的。所以它的大小应该在每次 DataBinding 操作完成时改变。这是触发重新计算 DataGridView 大小的条件。所以我把它挂到DataBindingComplete事件上。

  • 我的网格不应该显示滚动条。所以我将该Scrollbars属性设置为无。

  • 我的行和列自动调整模式设置为 AllCells。

  • 行和列标题不可见。如果是,则必须将其大小包括在计算中。

The extension below method fits my needs. It is very simple because my grids are very simple. You will probably have to tweak it a bit to make it work as you wish, and a lotto make it work for every DataGridView scenarios.

下面的扩展方法符合我的需要。这很简单,因为我的网格非常简单。你可能将不得不调整它有点让你想它的工作,和很多,使之成为每一个场景的DataGridView工作。

public static void HandleAutoSize(this DataGridView dgv)
{
    dgv.DataBindingComplete += (s, e) =>
    {
        var dg = (DataGridView)s;
        var width = dg.Columns.GetColumnsWidth(DataGridViewElementStates.None);
        var height = dg.Rows.GetRowsHeight(DataGridViewElementStates.None);

        dg.ClientSize = new Size(width, height);
    };
}

回答by Ranhiru Jude Cooray

回答by twip

This VB.NETtranslation worked for me:

这个VB.NET翻译对我有用:

For i As Integer = 0 To dataGridView.ColumnCount - 1
    dataGridView.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next

回答by Vikash Singh

The thread is quite old, but in case someone still needs it now he can use grid.AutoResizeColumns() works fine with me

该线程很旧,但如果现在有人仍然需要它,他可以使用 grid.AutoResizeColumns() 对我来说很好用

回答by Motes

The Real Answer

真正的答案

I wrote this code to calculate the exact size of the grid using pixel color and comparing it the background. It works great for me. It causes some flicker if you use autosize on the containing form, you must disable autosize or modify the code to manually set the size on the containing form. But, without autosize on the parent control it works perfectly.

我编写了这段代码来使用像素颜色计算网格的确切大小并将其与背景进行比较。这对我很有效。如果您在包含表单上使用自动调整大小,它会导致一些闪烁,您必须禁用自动调整大小或修改代码以手动设置包含表单的大小。但是,如果没有在父控件上自动调整大小,它就可以完美运行。

 private void gridViewAutoSize(DataGridView dgv)
        {

            Bitmap dgvBmp = new Bitmap(dgv.Width,dgv.Height);
            dynRecDataGridView.DrawToBitmap(dgvBmp, new Rectangle(0, 0, dgv.Width, dgv.Height));

            int x = dgv.Width-1;
            int y = dgv.Height-1;
            int halfHeaderW = dgv.RowHeadersWidth / 2;
            int halfHeaderH = dgv.ColumnHeadersHeight / 2;
            int borderX = 0;
            int borderY = 0;
            const int widthLimit = 800;
            const int heightLimit = 350;

            while (x == dgv.Width - 1)
            {
                borderX = 0;
                while (x >= 0 && dgvBmp.GetPixel(x, halfHeaderH).ToArgb() != dgv.BackgroundColor.ToArgb())
                {
                    borderX++;
                    x--;
                }
                if (x < 0)
                {
                    if(dgv.Width-1 <= widthLimit)
                    {
                        dgv.Width += 100;
                        dgvBmp = new Bitmap(dgv.Width, dgv.Height);
                        dynRecDataGridView.DrawToBitmap(dgvBmp, new Rectangle(0, 0, dgv.Width, dgv.Height));

                        x = dgv.Width - 1;
                    }
                    else
                    {
                        x = widthLimit;
                        borderX = 0;
                    }
                }
            }
            if (x > widthLimit)
            {
                x = widthLimit;
                borderX = 0;
            }
            else if(x < widthLimit)
            {
                while (dgvBmp.GetPixel(x, halfHeaderH).ToArgb() == dgv.BackgroundColor.ToArgb())
                {
                    x--;
                }
            }
            while (y == dgv.Height - 1)
            {
                borderY = 0;
                while (y >= 0  && dgvBmp.GetPixel(halfHeaderW, y).ToArgb() != dgv.BackgroundColor.ToArgb())
                {
                    borderY++;
                    y--;
                }
                if (y < 0)
                {
                    if (dgv.Height-1 <= heightLimit)
                    {
                        dgv.Height += 100;
                        dgvBmp = new Bitmap(dgv.Width, dgv.Height);
                        dynRecDataGridView.DrawToBitmap(dgvBmp, new Rectangle(0, 0, dgv.Width, dgv.Height));

                        y = dgv.Height - 1;
                    }
                    else
                    {
                        y = heightLimit;
                        borderY = 0;
                    }
                }
            }
            if (y > heightLimit)
            {
                y = heightLimit;
                borderY = 0;
            }
            else if (y < heightLimit)
            {
                while (dgvBmp.GetPixel(halfHeaderW, y).ToArgb() == dgv.BackgroundColor.ToArgb())
                {
                    y--;
                }
            }

            dgv.Size = new Size(x+borderX+1, y+borderY+1);

        }

回答by Ali Gubran

you can just change dataGridView properties To

您可以将 dataGridView 属性更改为

dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;