C# 无法以编程方式更改 gridview 列宽
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/934773/
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
Unable to change the gridview column width programatically
提问by SO User
On my windows form, I need to programatically set the width of columns in the grid view. I am using the following code:
在我的 windows 窗体上,我需要以编程方式设置网格视图中的列宽。我正在使用以下代码:
this.dgridv.Columns[columnName].Width = columnWidth;
The above stmt runs without any error. But, the column width remains unchanged. If I insert a breakpoint and check the value of width after the stmt runs, it is still 100, which I guess is the default value of datagrid column width.
上面的 stmt 运行没有任何错误。但是,列宽保持不变。如果我在stmt运行后插入断点并检查width的值,它仍然是100,我猜这是datagrid列宽的默认值。
Is there something else I need to do apart from this? Are there any values I need to set before changing the column width?
除了这个,我还有什么需要做的吗?在更改列宽之前是否需要设置任何值?
Any help or pointers on this are highly appreciated.
对此的任何帮助或指示都非常感谢。
Thanks :)
谢谢 :)
采纳答案by SO User
This worked:
这有效:
this.dgridv.Columns[columnName].AutoSizeMode= DataGridViewAutoSizeColumnMode.None;
this.dgridv.Columns[columnName].Width = columnWidth;
To reset it back, I am using:
要重置它,我正在使用:
dgvCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
回答by ChrisF
Have you got the AutoSizeColumnsMode
set to Fill?
你有AutoSizeColumnsMode
填充的设置吗?
If you have you'll need to set the FillWeight
property instead. This isn't a simple width but the proportion of width / no. columns
that this column takes up.
如果你有,你需要设置FillWeight
属性。这不是一个简单的宽度,而是width / no. columns
该列所占的比例。
If you haven't resized the columns it will be 100.0.
如果您还没有调整列的大小,它将是 100.0.0。
If the column has been widened it will be > 100.0.
如果该列已加宽,它将 > 100.0。
If the column has been shrunk it will be < 100.0.
如果列已缩小,它将 < 100.0。
Widening one column, by definition, shrinks the rest.
根据定义,扩大一栏会缩小其余栏。
回答by Ammar
dataGridView1.Columns[index].Width = 150;
dataGridView1.Columns[index].Width = 150;
This line of code will set the column width programatically.
这行代码将以编程方式设置列宽。