实现的方式有好几种。之前使用的是下面这种在RowPostPaint
事件中实现,效率不高。每次改变控件尺寸时都会执行
private void MsgGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e){DataGridView gdView = sender as DataGridView;System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,e.RowBounds.Location.Y,gdView.RowHeadersWidth - 4,e.RowBounds.Height);TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),gdView.RowHeadersDefaultCellStyle.Font,rectangle,gdView.RowHeadersDefaultCellStyle.ForeColor,TextFormatFlags.VerticalCenter | TextFormatFlags.Right);}
为了消除更新所带来的的闪屏问题,需要开启窗体和控件的双缓存,在窗体的构造函数中插入下面的代码。
private IGForm(){ //设置窗体的双缓冲 this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true); this.UpdateStyles();InitializeComponent(); // //利用反射设置DataGridView的双缓冲 Type dgvType = this.MsgGridView.GetType(); PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic); pi.SetValue(this.MsgGridView, true, null);}
===========================================
显示DataGridView背景颜色
//单元格样式的BackColor方法设置背景色DataGridView.RowsDefaultCellStyle.BackColor = Color.LightSteelBlue;//奇数行样式的BackColor方法设置DataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.LightSteelBlue;