DataGridView 自动调整和填充 [英] DataGridView AutoFit and Fill
问题描述
我的 DataGridView
中有 3 列.我想要做的是让前 2 列自动适应内容的宽度,并让第 3 列填充剩余空间.
I have 3 columns in my DataGridView
. What I am trying to do is have the first 2 columns auto fit to the width of the content, and have the 3rd column fill the remaining space.
是否可以在 WinForms 中进行?如果有任何用处,我正在从 EF DataContext 加载我的数据.我已经包含了它当前外观的图像.
Is it possible to do in WinForms? I am loading my data from an EF DataContext if that's any use. I have included an image of how it currently looks.
推荐答案
您需要使用 DataGridViewColumn.AutoSizeMode
属性.
You need to use the DataGridViewColumn.AutoSizeMode
property.
您可以为第 0 列和第 1 列使用以下值之一:
You can use one of these values for column 0 and 1:
AllCells: 调整列宽以适应所有单元格的内容列,包括标题单元格.
AllCellsExceptHeader: 调整列宽以适应列中所有单元格的内容,不包括标题单元格.
DisplayedCells: 列宽调整为适合当前在行中的列中所有单元格的内容显示在屏幕上,包括标题单元格.
DisplayedCellsExceptHeader: 调整列宽以适应当前在行中的列中所有单元格的内容显示在屏幕上,不包括标题单元格.
然后您使用 Fill 列 2 的值
Then you use the Fill value for column 2
调整列宽,使所有列的宽度正好填满控件的显示区域...
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
<小时>
正如其他用户所指出的,可以在 datagridview
级别使用 DataGridView.AutoSizeColumnsMode
属性.
As pointed out by other users, the default value can be set at datagridview
level with DataGridView.AutoSizeColumnsMode
property.
this.DataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
this.DataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
可能是:
this.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
<小时>
重要提示:
如果您的网格绑定到数据源并且列是自动生成的(AutoGenerateColumns
属性设置为 True),您需要使用 DataBindingComplete
事件以应用样式 AFTER 列已创建.
If your grid is bound to a datasource and columns are auto-generated (AutoGenerateColumns
property set to True), you need to use the DataBindingComplete
event to apply style AFTER columns have been created.
在某些情况下(例如通过代码更改单元格值),我不得不调用 DataGridView1.AutoResizeColumns();
来刷新网格.
In some scenarios (change cells value by code for example), I had to call DataGridView1.AutoResizeColumns();
to refresh the grid.
这篇关于DataGridView 自动调整和填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!