gpt4 book ai didi

c# - DataGridView 自动调整和填充

转载 作者:IT王子 更新时间:2023-10-29 03:40:27 25 4
gpt4 key购买 nike

我的 DataGridView 中有 3 列。我想要做的是让前 2 列自动适应内容的宽度,并让第 3 列填充剩余空间。

是否可以在 WinForms 中执行?如果有任何用处,我正在从 EF DataContext 加载我的数据。我附上了一张它目前的样子的图片。

enter image description here

最佳答案

您需要使用 DataGridViewColumn.AutoSizeMode属性(property)。

您可以为第 0 列和第 1 列使用以下值之一:

AllCells: The column width adjusts to fit the contents of all cells in the column, including the header cell.
AllCellsExceptHeader: The column width adjusts to fit the contents of all cells in the column, excluding the header cell.
DisplayedCells: The column width adjusts to fit the contents of all cells in the column that are in rows currently displayed onscreen, including the header cell.
DisplayedCellsExceptHeader: The column width adjusts to fit the contents of all cells in the column that are in rows currently displayed onscreen, excluding the header cell.

然后您对第 2 列使用 Fill

The column width adjusts so that the widths of all columns exactly fills the display area of the control...

this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

正如其他用户所指出的,默认值可以在 datagridview 级别设置为 DataGridView.AutoSizeColumnsMode属性(property)。

this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

可能是:

this.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

重要提示:

如果您的网格绑定(bind)到数据源并且列是自动生成的(AutoGenerateColumns 属性设置为 True),您需要使用 DataBindingComplete应用样式 AFTER 列的事件已创建。


在某些情况下(例如通过代码更改单元格值),我必须调用 DataGridView1.AutoResizeColumns(); 来刷新网格。

关于c# - DataGridView 自动调整和填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18666582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com