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);

最新文章

  1. WCF入门教程2——创建第一个WCF程序
  2. Python’s SQLAlchemy vs Other ORMs[转发 3]Django&#39;s ORM
  3. 一个Java内存可见性问题的分析
  4. CSS3+JS切割轮播图
  5. MyBatis入门(五)---延时加载、缓存
  6. 关于App.config配置文件
  7. ASCII与UNICODE的区别
  8. exists查询中子表可以是
  9. Heritrix源码分析(十五)
  10. 如何从本地把项目上传到github&amp;&amp;如何把github项目通过clone复制下来
  11. R︱shiny实现交互式界面布置与搭建(案例讲解+学习笔记)
  12. 解决Select标签的Option在IE浏览中display:none不生效的问题
  13. Lucene 06 - 使用Lucene的Query API查询数据
  14. CART回归树
  15. C# WinForm窗体隐藏右上角最小化、最大化、关闭按钮
  16. highcharts为X轴标签添加链接
  17. 集合总结(全是代码)----------java基础学习
  18. Python Django 之 直接执行自定义SQL语句(一)
  19. DEDECMS ShowMsg()样式修改 提示信息的修改以及美化
  20. [leetcode]381. Insert Delete GetRandom O(1) - Duplicates allowed常数时间插入删除取随机值

热门文章

  1. Python正则表达式re库的初次使用入门
  2. Nginx整数溢出漏洞 Writeup
  3. Lab: Brute-forcing a stay-logged-in cookie:点击保持登录状态返回的Cookie里面破解账号密码靶场复盘
  4. mysql--使用shardingsphere实现分表
  5. metasploit的数据库配置
  6. CentOS7 安装Oracle12c数据库
  7. Splay做题笔记
  8. Docker搭建网页数据库管理-Adminer
  9. Collectors.reducing总结
  10. mysql 局域网连接