调整DataGridView的宽度以适应列 [英] Resize DataGridView width to fit Columns

查看:275
本文介绍了调整DataGridView的宽度以适应列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataGridView ,以编程方式填充。这些列被设置为根据单元格内容自动调整大小。

I have a DataGridView that is filled programmatically. The columns are set to auto-resize according to cell content.

DataGridView 将填充有关液压和气动示意图。我的表单只有一个 SplitContainer ,一个 PictureBox DataGridView SplitterDistance 链接到 DataGridView 的宽度。

The DataGridView will be populated with parts information regarding hydraulic and pneumatic schematics. My form only has a SplitContainer, a PictureBox and the DataGridView. The SplitterDistance is linked to the width of the DataGridView.

DataGridView 最多只能包含6列(Index,Part Number,Serial Number,Drawing Number,Page数字,版本号),至少需要2列,具体取决于原理图要求。所以我想调整相应的控件大小。

The DataGridView will only have a maximum of 6 columns ("Index", "Part Number", "Serial Number", "Drawing Number", "Page Number", "Revision Number") and a minimum of 2 columns depending on the schematics requirements. So I want to resize the control accordingly.

如何获取$ $ $ $ $ $ $ $ $ $ $ $的列,以便滚动条不显示?

How can I get the DataGridView control to resize to the total width of the columns so that the scrollbar doesn't show?

推荐答案

在网格加载数据后执行以下代码,列已经相应地进行了大小(假设您在运行时设置列的AutoSize属性)。

Execute the following code after the grid is loaded with data and the columns have been sized accordingly (assuming you're setting the columns' AutoSize property at runtime).

dataGridView1.Width =
    dataGridView1.Columns.Cast<DataGridViewColumn>().Sum(x => x.Width)
    + (dataGridView1.RowHeadersVisible ? dataGridView1.RowHeadersWidth : 0) + 3;

正在做什么:


  • 统计所有列的宽度(使用LINQ),

  • 如果行标题可见,并添加该宽度,如果是,

  • 添加 3 更多,因为没有水平滚动条不断显示 - 可能是因为网格周围的边距/填充,我不知道。

  • Totals up the widths of all columns (using LINQ),
  • Sees if the "row header" is visible and adds that width too, if it is,
  • Adds 3 more because without that the horizontal scrollbar kept showing up - possibly because of margin/padding around the grid, I'm not sure.

这篇关于调整DataGridView的宽度以适应列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆