【WinForms】DataGridView自动调整列宽度以及最后一列宽度填充
直接上代码。
using System; using System.Data; using System.Linq; using System.Reflection; using System.Windows.Forms; namespace DataGridViewTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // 数据量很大时,开启双缓冲绘制可以明显提高表格绘制速度,减少拖动滚动条时卡顿 typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView1, new object[] { true }); // 禁止添加行 dataGridView1.AllowUserToAddRows = false; // 禁止删除行 dataGridView1.AllowUserToDeleteRows = false; // 禁止排序列 dataGridView1.AllowUserToOrderColumns = false; // 禁止调整列宽 dataGridView1.AllowUserToResizeColumns = false; // 禁止调整行高 dataGridView1.AllowUserToResizeRows = false; // 隐藏行头 dataGridView1.RowHeadersVisible = false; // 整行选择 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 禁止编辑 dataGridView1.ReadOnly = true; // 自动调整列宽 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; // 当DataSource赋值时自动生成对应的列(此属性默认为True) dataGridView1.AutoGenerateColumns = true; } private static readonly Random _random = new Random(); private static Record MakeRecord(int index) { return new Record { Id = index, InputVoltage = (float)_random.Next(490, 510) / 100, InputCurrent = (float)_random.Next(990, 1190) / 1000, OutputVoltage = (float)_random.Next(490, 510) / 100, OutputCurrent = (float)_random.Next(990, 1190) / 1000, Efficiency = (float)_random.Next(8000, 9000) / 100, Step = 1, Time = DateTime.Now }; } private void button1_Click(object sender, EventArgs e) { // 生成50000条数据 Record[] data = Enumerable.Range(1, 50000).Select(MakeRecord).ToArray(); // 赋值数据源,根据设置,自动生成所有对应的列 dataGridView1.DataSource = data; // 设置最后一列宽度填满控件 DataGridViewColumn column = dataGridView1.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None); if (column != null) { column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; } } } class Record { public int Id { get; set; } public float InputVoltage { get; set; } public float InputCurrent { get; set; } public float OutputVoltage { get; set; } public float OutputCurrent { get; set; } public float Efficiency { get; set; } public int Step { get; set; } public DateTime Time { get; set; } } }