DataGridView高度自动调整
2024-09-01 01:09:54
AutoResizeGrid.cs代码
/// <summary>
/// 根据行数据,自动调整DataGridView高度
/// </summary>
public sealed partial class AutoResizeGrid
{
private readonly DataGridView DataGrid;
private readonly int MaxHeight;
/// <summary>
/// 是否自动调整
/// </summary>
private bool IsAutoResize = true; /// <summary>
/// 构造函数
/// </summary>
/// <param name="dataGridView"></param>
/// <param name="maxHeight">最大高度,-1 时不限制高度</param>
public AutoResizeGrid(DataGridView dataGridView, int maxHeight = -1)
{
this.DataGrid = dataGridView;
this.MaxHeight = maxHeight; if (this.IsAutoResize)
{
this.DataGrid.RowsAdded += DataGrid_RowsAdded;
}
} /// <summary>
/// 行添加后事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
this.UpdateGridHeight();
} /// <summary>
/// 计算实际高度
/// </summary>
/// <returns></returns>
public int GetFactHeight()
{
// 计算实际高度
var rowsHeight = this.DataGrid.Rows.GetRowsHeight(DataGridViewElementStates.Visible);
var headHeight = this.DataGrid.ColumnHeadersHeight; return (rowsHeight + headHeight);
} /// <summary>
/// 更新高度,调用时机,添加数据行后调用
/// </summary>
private void UpdateGridHeight()
{
// 计算实际高度
// 多增加一行,否则会有滚动条
var factHeight = this.GetFactHeight() + this.GetHScrollBarHeight();
if (-1 == this.MaxHeight)
{
this.DataGrid.Height = factHeight;
}
else
{
this.DataGrid.Height = Math.Min(this.MaxHeight, factHeight);
}
}
/// <summary>
/// 获取水平滚动条高度
/// </summary>
/// <returns></returns>
private int GetHScrollBarHeight()
{
var height = 2;
foreach (Control ctrl in this.DataGrid.Controls)
{
if (ctrl.AccessibilityObject.ToString().IndexOf("System.Windows.Forms.HScrollBar") > 0)
{
if (ctrl.Visible)
{
// do something
return (height + ctrl.Height);
}
}
} return height;
}
}
使用方式
new AutoResizeGrid(this.dataGridView1, maxHeight: 200);
最新文章
- WCF入门教程2——创建第一个WCF程序
- Python’s SQLAlchemy vs Other ORMs[转发 3]Django&#39;s ORM
- 一个Java内存可见性问题的分析
- CSS3+JS切割轮播图
- MyBatis入门(五)---延时加载、缓存
- 关于App.config配置文件
- ASCII与UNICODE的区别
- exists查询中子表可以是
- Heritrix源码分析(十五)
- 如何从本地把项目上传到github&;&;如何把github项目通过clone复制下来
- R︱shiny实现交互式界面布置与搭建(案例讲解+学习笔记)
- 解决Select标签的Option在IE浏览中display:none不生效的问题
- Lucene 06 - 使用Lucene的Query API查询数据
- CART回归树
- C# WinForm窗体隐藏右上角最小化、最大化、关闭按钮
- highcharts为X轴标签添加链接
- 集合总结(全是代码)----------java基础学习
- Python Django 之 直接执行自定义SQL语句(一)
- DEDECMS ShowMsg()样式修改 提示信息的修改以及美化
- [leetcode]381. Insert Delete GetRandom O(1) - Duplicates allowed常数时间插入删除取随机值