C# 自动调整表单到 DataGridView 的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1607790/
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-08-06 19:19:53  来源:igfitidea点击:

C# Auto Resize Form to DataGridView's size

c#formsdatagridviewresize

提问by akif

I have a Form and a DataGridView. I populate the DataGridView at runtime, so I want to know how do I resize the Form dynamically according to the size of the DataGridView? Is there any sort of property or method? Or do I have to determine the size myself and update accordingly?

我有一个表单和一个 DataGridView。我在运行时填充 DataGridView,所以我想知道如何根据 DataGridView 的大小动态调整 Form 的大小?有什么属性或方法吗?还是我必须自己确定尺寸并相应地更新?

回答by MusiGenesis

Normally controls adapt their sizes to the size of the containing form. To adjust the size of your form to the size of your DataGridView, you dohave to determine the size yourself and then set the form's size to match, remembering to take into account the extra size required by the form's menu strip and/or toolbars, status bars or other controls.

通常,控件会根据包含表单的大小调整它们的大小。要调整表格到您的DataGridView的尺寸大小,你必须确定自己的大小,然后设置窗体的大小比赛,记住要考虑到窗体的菜单条和/或工具栏所需的额外的大小,状态栏或其他控件。

In your case, it would probably be best not to resize the form to match the grid view control. Most likely, you will have many more rows in your grid view than could fit on your Windows screen, and you don't want to have a form that extends below the viewable desktop area. Generally speaking, this type of situation is exactly why you want to have a scrollable grid view - for viewing more data than can fit on the screen at one time.

在您的情况下,最好不要调整表单的大小以匹配网格视图控件。最有可能的是,您的网格视图中的行数将超过 Windows 屏幕所能容纳的行数,并且您不希望表单扩展到可查看桌面区域下方。一般来说,这种情况正是您想要一个可滚动的网格视图的原因 - 用于查看一次屏幕上无法容纳的更多数据。

回答by Artru

You can find the actual width by count Columns width.

您可以通过计数列宽度找到实际宽度。

Don't forget that your form may be more complex and your should count other controls.

不要忘记您的表单可能更复杂,您应该计算其他控件。

public class YourForm : Form
{
    public YourForm()
    {
        DataGridView _dgv = new DataGridView() { Dock = DockStyle.Fill};
        Controls.Add(_dgv);
    }
    public void CorrectWindowSize()
    {
        int width = WinObjFunctions.CountGridWidth(_dgv);
        ClientSize = new Size(width, ClientSize.Height);
    }
    DataGridView _dgv;
}

public static class WinObjFunctions
{
    public static int CountGridWidth(DataGridView dgv)
    {
        int width = 0;
        foreach (DataGridViewColumn column in dgv.Columns)
            if (column.Visible == true)
                width += column.Width;
        return width += 20;
    }
}

回答by JMB

I would go the other direction and size the grid to the form. (some users may have low res) Set 'WindowState' property of the form => maximized. (optional) Set 'anchor' property of the DGV => 'Top, Bottom, Left, Right'.

我会去另一个方向并将网格的大小调整为表格。(某些用户可能分辨率较低)设置窗体的 'WindowState' 属性 => 最大化。(可选)设置 DGV 的“锚点”属性 =>“顶部、底部、左侧、右侧”。

回答by amacleod

You may be able to make use of the PreferredSizeproperty (MSDN PreferredSize entry). For DataGridViewcontrols, I found that the preferred width and height were about 20 units bigger than I expected. I guess that the control might be calculating its preferred size taking scroll bars into account.

您可以使用该PreferredSize属性(MSDN PreferredSize 条目)。对于DataGridView控件,我发现首选的宽度和高度比我预期的大 20 个单位。我猜想控件可能正在计算其首选大小,并考虑到滚动条。

Another caveat I discovered is that the PreferredSizecalculation will not be accurate immediately after adding or changing items in the table. To get around this I made a handler for the RowHeadersWidthChangedevent.

我发现的另一个警告是,PreferredSize在表中添加或更改项目后,计算不会立即准确。为了解决这个问题,我为该RowHeadersWidthChanged事件创建了一个处理程序。

Here is what worked for me:

这是对我有用的:

class GridToy {
    private DataGridView grid;
    public GridToy(DataGridView dgv) {
        grid = dgv;
        grid.RowHeadersWidthChanged += AdjustWidth; // Event handler.
        Layout();
    }

    public void Layout() {
        // Just do some arbitrary manipulation of the grid.
        grid.TopLeftHeaderCell.Value = "Some Arbitrary Title";
    }

    public void AdjustWidth() {
        Control horizontal = grid.Controls[0]; // Horizontal scroll bar.
        Control vertical = grid.Controls[1]; // Vertical scroll bar.
        grid.Width = grid.PreferredSize.Width - vertical.Width + 1;
        grid.Height = grid.PreferredSize.Height - horizontal.Height + 1;
    }
}

回答by T30

int dgv_width = dataGridView1.Columns.GetColumnsWidth(DataGridViewElementStates.Visible);
int dgv_height = dataGridView1.Rows.GetRowsHeight(DataGridViewElementStates.Visible);
this.Width = dgv_width;
this.Height = dgv_height;

this.Widthresizes this Form width.

this.Width调整此表单宽度的大小。

Of course you've to add fixed values (for example margin, Form title heigth, ecc.). With tests i've reached the values working for me (don't ask why...):

当然,您必须添加固定值(例如边距、表单标题高度等)。通过测试,我已经达到了对我有用的值(不要问为什么......):

this.Width = dgv_width + 147;
this.Height = dgv_height + 47;

回答by Omaralajlan

You could set the Property " Height " to Auto in the form after classifying or using an ID and this should do it ,,

您可以在分类或使用 ID 后在表单中将属性“高度”设置为自动,这应该这样做,

I just tried it .. and It worked

我刚试过..它奏效了

#form1{
 background-color:white;
 height:auto;                             
 width:1500px;              
 border-top:medium solid #3399FF;
 margin-top:100px;
 margin-left:30px;
 display: inline-block;
 text-align: center;                
 float: none;      
}

I'm just putting exactly what I did in case you got lost .. Don't worry about the other properties there for my design.

我只是把我做的完全一样,以防万一你迷路了..不要担心我设计的其他属性。

回答by Anuja

Set AutoSizeColumnsMode :Fillin Grid Properties

AutoSizeColumnsMode :Fill在网格属性中设置