C# 调整DataGridView宽度以适合列

C# 调整DataGridView宽度以适合列,c#,winforms,datagridview,C#,Winforms,Datagridview,我有一个DataGridView,它是以编程方式填充的。列设置为根据单元格内容自动调整大小 DataGridView将填充有关液压和气动示意图的零件信息。我的表单只有一个SplitContainer、一个PictureBox和DataGridView。SplitterDistance链接到DataGridView的宽度 DataGridView最多只能有6列(“索引”、“零件号”、“序列号”、“图纸号”、“页码”、“修订号”),至少有2列,具体取决于原理图要求。所以我想相应地调整控件的大小 如何

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

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

DataGridView
最多只能有6列(“索引”、“零件号”、“序列号”、“图纸号”、“页码”、“修订号”),至少有2列,具体取决于原理图要求。所以我想相应地调整控件的大小


如何使
DataGridView
控件调整到列的总宽度,以便不显示滚动条?

在网格加载数据并相应调整列的大小后执行以下代码(假设在运行时设置列的AutoSize属性)

dataGridView1.Width=
dataGridView1.Columns.Cast().Sum(x=>x.Width)
+(dataGridView1.RowHeadersVisible?dataGridView1.RowHeadersWidth:0)+3;
它在做什么:

  • 合计所有列的宽度(使用LINQ)
  • 查看“行标题”是否可见并添加该宽度(如果可见)
  • 添加
    3
    更多,因为如果没有它,水平滚动条会一直显示出来-可能是因为网格周围的边距/填充,我不确定

好的,澄清你想要什么(并回答)

我想您想让DataGridView宽度在大小上扩展,这样就不会出现水平滚动条了?(顺便说一句,你可以增加包含它的表单)

例如,现在我有

那里有一列1、2和3

我希望datagridview扩展到适合所有列的大小

假设添加了更多的数据

我可以用这两行来扩展细胞

dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; 
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
但我仍然得到一个水平滚动条,因为datagridview的大小没有改变。即使每列的大小都已更改

我可以看到有一个datagridview1.Size属性和一个datagridview1.Width属性。两者都可以使用

还要注意,在第一列之前有一个有趣的列

因此,如果您确实使dataGridView1.Width等于cols 1,2,3的大小,您仍然会有一个滚动条,因为在列左侧标记为“column 1”的地方有一个有趣的类似列的东西。我看到它有50个单位的宽度。因此,如果将dataGridView1.Width=50加上每列的宽度,那么灰色的dataGridView区域将始终足够大,足以包含所有列

我画了一个datagridview和一个textbox,textbox显示datagridview的大小。所有列的宽度和总宽度,以及每个列的宽度

这对我有用

因此,列被设置为根据其中的内容量进行大小扩展或减小,但不仅如此。。宽度将增加50(最左边的有趣列),加上所有常规/其余列的大小

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace automaticallyexpanddatagridviewsizeandformsize
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          //  MessageBox.Show(dataGridView1.Size.Width.ToString());

            // note that with these two set you can't change the width of a column
            // also  MininimumWidth would limit changing the width of a column too, 
            //http://stackoverflow.com/questions/2154154/datagridview-how-to-set-column-width
            // but that doesn't matter because we aren't programmatically changing the width of any column.

            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; 
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;




        }



        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

            int olddgvsize = dataGridView1.Width;

            textBox1.Text = dataGridView1.Columns[0].Width.ToString();
            int h=dataGridView1.Height;

            int tw = 0;
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
              //  MessageBox.Show(dataGridView1.Columns[i].Width.ToString());
                tw += dataGridView1.Columns[i].Width;

            }
            tw += 50; // column before col 0..

           //you only need one of these.
           //though to better understand the code you can try to comment out both and see how the total width of all columns (tw)(+50) so ALL the columns, differs from  the DataGridView.Width (the total area which includes all columns plus some grey if it's much bigger than all the columns)

            dataGridView1.Size = new Size(tw, h);
            dataGridView1.Width = tw;

                textBox1.Text = "tw=" + tw + " " + "dgvw=" + " " +dataGridView1.Width+ "  "+"col 1:" + dataGridView1.Columns[0].Width + " col 2:"  + dataGridView1.Columns[1].Width + " col 3:"+ dataGridView1.Columns[2].Width;

                int newdgvsize = dataGridView1.Width;
                int differenceinsizeofdgv = newdgvsize - olddgvsize;
                this.Width = this.Width + differenceinsizeofdgv;


        }


    }



}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
命名空间自动扩展DataGridViewSizeAndForMsize
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
//Show(dataGridView1.Size.Width.ToString());
//请注意,使用这两个设置,您无法更改列的宽度
//此外,MininimumWidth也会限制更改列的宽度,
//http://stackoverflow.com/questions/2154154/datagridview-how-to-set-column-width
//但这并不重要,因为我们不会以编程方式更改任何列的宽度。
dataGridView1.AutoSizeRowsMode=DataGridViewAutoSizeRowsMode.AllCells;
dataGridView1.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;
}
私有void dataGridView1_CellEndEdit(对象发送方,DataGridViewCellEventArgs e)
{
int olddgvsize=dataGridView1.Width;
textBox1.Text=dataGridView1.Columns[0].Width.ToString();
int h=dataGridView1.1高度;
int-tw=0;
对于(int i=0;i
比如我有

tw是所有列(所有列)的总宽度,因此包括第1列左侧的怪异列,即
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace automaticallyexpanddatagridviewsizeandformsize
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          //  MessageBox.Show(dataGridView1.Size.Width.ToString());

            // note that with these two set you can't change the width of a column
            // also  MininimumWidth would limit changing the width of a column too, 
            //http://stackoverflow.com/questions/2154154/datagridview-how-to-set-column-width
            // but that doesn't matter because we aren't programmatically changing the width of any column.

            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; 
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;




        }



        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

            int olddgvsize = dataGridView1.Width;

            textBox1.Text = dataGridView1.Columns[0].Width.ToString();
            int h=dataGridView1.Height;

            int tw = 0;
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
              //  MessageBox.Show(dataGridView1.Columns[i].Width.ToString());
                tw += dataGridView1.Columns[i].Width;

            }
            tw += 50; // column before col 0..

           //you only need one of these.
           //though to better understand the code you can try to comment out both and see how the total width of all columns (tw)(+50) so ALL the columns, differs from  the DataGridView.Width (the total area which includes all columns plus some grey if it's much bigger than all the columns)

            dataGridView1.Size = new Size(tw, h);
            dataGridView1.Width = tw;

                textBox1.Text = "tw=" + tw + " " + "dgvw=" + " " +dataGridView1.Width+ "  "+"col 1:" + dataGridView1.Columns[0].Width + " col 2:"  + dataGridView1.Columns[1].Width + " col 3:"+ dataGridView1.Columns[2].Width;

                int newdgvsize = dataGridView1.Width;
                int differenceinsizeofdgv = newdgvsize - olddgvsize;
                this.Width = this.Width + differenceinsizeofdgv;


        }


    }



}
private void Form1_Load(object sender, EventArgs e)
{
    //Create datagridview and button below it.

    DataGridView dgv = new DataGridView();
    dgv.Columns.Add("Column1","Column1");
    dgv.Rows.Add(2);
    dgv.AllowUserToAddRows = false;
    this.Controls.Add(dgv);

    dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
    dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

    int tw;

    tw = dgv.Columns.GetColumnsWidth(DataGridViewElementStates.None) + dgv.RowHeadersWidth + 2;
    dgv.Width = tw;

    // the cellleave, is done before the autoresize.
    // but performing a button click, that triggers a cell autoresize!
    //performing a click to a button added to the form..does the autoresize.
    // so the resie has to be done after the click... either in the click code, or in the celleave procedure after the performclick.

    Button by = new Button();
    this.Controls.Add(by); // necessary for the dgv to resize
    // but doesn't need the code to necessarily be within the click.

    by.Click += (object ssender, EventArgs ee) => { };

    dgv.CellEndEdit += (object ssender, DataGridViewCellEventArgs ee) => {
        by.PerformClick();
        tw = dgv.Columns.GetColumnsWidth(DataGridViewElementStates.None) + dgv.RowHeadersWidth + 2;
        dgv.Width = tw;
    };

}