好吧,澄清你想要什么(并回答它)
我想你想让 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和一个文本框,文本框显示了datagridview.Width的大小和所有列的总宽度,以及每一列的宽度。
这对我有用。
因此,根据其中的内容量,将列设置为扩大或缩小大小,但不仅如此.. DataGridView.Width 将增加 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;
}
}
}
所以例如我有
tw 是所有列的总宽度(所有列,包括第 1 列左侧的奇怪列,我认为它的宽度为 50,也许是这样)
dgvw 是 dataGridView.Width
感谢上面的代码,dgvw 用 tw 扩展。
上面的代码也将表单扩展了dataGridView扩展的量。