【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; }
datagridview数据源public float Efficiency { get; set; }
public int Step { get; set; }
public DateTime Time { get; set; } }
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论