C# 如何自动调整 DataGridView 控件中的列大小并允许用户调整同一网格上的列大小?

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

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

c#winformsdatagridview

提问by Stuart Helwig

I am populating a DataGridView control on a Windows Form (C# 2.0 not WPF).

我正在 Windows 窗体(C# 2.0 不是 WPF)上填充 DataGridView 控件。

My goal is to display a grid that neatly fills all available width with cells - i.e. no unused (dark grey) areas down the right and sizes each column appropriately according to the data it contains, butalso allows the user to resize any of the columns to their liking.

我的目标是显示一个网格,用单元格整齐地填充所有可用宽度 - 即右侧没有未使用的(深灰色)区域,并根据其包含的数据适当调整每列的大小,也允许用户调整任何列的大小随心所欲。

I am attempting to achieve this by setting the AutoSizeMode of each column to be DataGridViewAutoSizeColumnMode.AllCellsexcept for one of the columns which I set to DataGridViewAutoSizeColumnMode.Fillin order to ensure the entire area of the grid is neatly filled with data. (I don't mind that when the user attempt to resize this column it springs back to a size that ensures the horizontal space is always used.)

我试图通过将每列的 AutoSizeMode 设置为DataGridViewAutoSizeColumnMode.AllCells来实现这一点,但我设置为DataGridViewAutoSizeColumnMode.Fill的列之一除外,以确保网格的整个区域都整齐地填充了数据。(我不介意当用户尝试调整此列的大小时,它会弹回到确保始终使用水平空间的大小。)

However, as I mentioned, once loaded I would like to allow the user to resize the columns to suit their own requirements - in setting these AutoSizeMode values for each column it appears the user is then unable to then resize those columns.

然而,正如我所提到的,一旦加载,我希望允许用户调整列的大小以满足他们自己的要求 - 在为每列设置这些 AutoSizeMode 值时,用户似乎无法再调整这些列的大小。

I've tried not setting the AutoSizeMode of all the columns which does allow resizing BUT doesn't set the initial size according to the data the cells contain. The same result occurs when changing the grid's AutoSizeMode back to "Not Set" after loading the data.

我试过不设置允许调整大小的所有列的 AutoSizeMode 但不根据单元格包含的数据设置初始大小。在加载数据后将网格的 AutoSizeMode 更改回“未设置”时会出现相同的结果。

Is there a setting I'm missing here which allows automatic setting of default column widths AND user resizing or is there another technique I must use when populating the DataGridView control?

这里是否缺少允许自动设置默认列宽和用户调整大小的设置,或者在填充 DataGridView 控件时是否必须使用另一种技术?

采纳答案by Miroslav Zadravec

This trick works for me:

这个技巧对我有用:

grd.DataSource = DT;

//set autosize mode
grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
grd.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
grd.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

//datagrid has calculated it's widths so we can store them
for (int i = 0; i <= grd.Columns.Count - 1; i++) {
    //store autosized widths
    int colw = grd.Columns[i].Width;
    //remove autosizing
    grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    //set width to calculated by autosize
    grd.Columns[i].Width = colw;
}

What happens here is that you set autosize to whathever mode you need and then column by column you store the width it got from autosize calculation, remove autosizing and set width to value you stored before.

这里发生的事情是您将自动调整大小设置为您需要的任何模式,然后逐列存储从自动调整大小计算中获得的宽度,删除自动调整大小并将宽度设置为您之前存储的值。

回答by Jehof

In my application I have set

在我的应用程序中,我设置了

grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;

Also, I have set the

另外,我已经设置了

grid.AllowUserToOrderColumns = true;
grid.AllowUserToResizeColumns = true;

Now the column widths can be changed and the columns can be rearranged by the user. That works pretty well for me.

现在可以更改列宽,用户可以重新排列列。这对我来说效果很好。

Maybe that will work for you.

也许这对你有用。

回答by Umair

Maybe you could call

也许你可以打电话

dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill);

After setting datasource. It will set the width and allow resize.

设置数据源后。它将设置宽度并允许调整大小。

More on MSDN DataGridView.AutoResizeColumns Method (DataGridViewAutoSizeColumnsMode).

有关 MSDN DataGridView.AutoResizeColumns 方法 (DataGridViewAutoSizeColumnsMode) 的更多信息

回答by Gorgsenegger

If I understood the question correctly there should be an easier way to accomplish what you need. Call dgvSomeDataGrid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

如果我正确理解了这个问题,那么应该有一种更简单的方法来完成您的需求。称呼 dgvSomeDataGrid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

That should do the trick. However, there is one pitfall as you cannot simply call this method directly after populating your DataGridView control. Instead you will have to add an EventHandler for the VisibleChanged event and call the method in there.

这应该够了吧。但是,存在一个缺陷,因为您不能在填充 DataGridView 控件后直接调用此方法。相反,您必须为 VisibleChanged 事件添加一个 EventHandler 并在其中调用该方法。

回答by Aleksei Rubanovskii

Did you try to set up the FillWeightproperty of your DataGridViewColumnsobject?

您是否尝试设置对象的FillWeight属性DataGridViewColumns

For example:

例如:

this.grid1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.grid1.Columns[0].FillWeight = 1.5;

I think it should work in your case.

我认为它应该适用于您的情况。

回答by Tom Kidd

A C# version of Miroslav Zadravec's code

Miroslav Zadravec 代码的 AC# 版本

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

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    int colw = dataGridView1.Columns[i].Width;
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dataGridView1.Columns[i].Width = colw;
}

Posted as Community Wiki so as to not mooch off of the reputation of others

作为社区 Wiki 发布,以免影响他人的声誉

回答by mpss

Well, I did this like this:

好吧,我是这样做的:

dgvReport.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
dgvReport.AutoResizeColumns();
dgvReport.AllowUserToResizeColumns = true;
dgvReport.AllowUserToOrderColumns = true;

in that particular order. Columns are resized (extended) AND the user can resize columns afterwards.

以那个特定的顺序。列被调整大小(扩展)并且用户可以在之后调整列大小。

回答by Rob

Slightly neater C# code from Miroslav Zadravec's code assuming all columns are to be autosized

假设所有列都自动调整大小,Miroslav Zadravec 代码中的 C# 代码稍微简洁一些

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

回答by Initrof

A little improvement from Schnapple's version

比 Schnapple 的版本稍有改进

int nLastColumn = dgv.Columns.Count - 1;
for (int i = 0; i < dgv.Columns.Count; i++)
{
    if (nLastColumn == i)
    {
        dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    }
    else
    {
        dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }
}

for (int i = 0; i < dgv.Columns.Count; i++)
{
    int colw = dgv.Columns[i].Width;
    dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dgv.Columns[i].Width = colw;
}

回答by wnutt

This autofits all columns according to their content, fills the remaining empty space by stretching a specified column and prevents the 'jumping' behaviour by setting the last column to fill for any future resizing.

这会根据它们的内容自动调整所有列,通过拉伸指定的列来填充剩余的空白空间,并通过将最后一列设置为填充以供将来调整大小来防止“跳跃”行为。

// autosize all columns according to their content
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
// make column 1 (or whatever) fill the empty space
dgv.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
// remove column 1 autosizing to prevent 'jumping' behaviour
dgv.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
// let the last column fill the empty space when the grid or any column is resized (more natural/expected behaviour) 
dgv.Columns.GetLastColumn(DataGridViewElementStates.None, DataGridViewElementStates.None).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;