DataGridView添加行号

自己在做WINFORM小玩意的时候需要在datagridview上显示行号,上网搜索一下,找到如下代码,不错,先记录下来了。

    在RowPostPaint事件中画出来

         //  绘制行号
         private   void  gvdata_RowPostPaint( object  sender, DataGridViewRowPostPaintEventArgs e)
        {
            
try
            {

                Rectangle rectangle 
=   new  Rectangle(e.RowBounds.Location.X,

                    Convert.ToInt32(e.RowBounds.Location.Y 
+  (e.RowBounds.Height  -  gvdata.RowHeadersDefaultCellStyle.Font.Size)  /   2 ),

                    gvdata.RowHeadersWidth 
-   4 , e.RowBounds.Height);

                TextRenderer.DrawText(e.Graphics, (e.RowIndex 
+   1 ).ToString(),

                    gvdata.RowHeadersDefaultCellStyle.Font, rectangle, gvdata.RowHeadersDefaultCellStyle.ForeColor,

                    TextFormatFlags.Right);



            }

            
catch  (Exception ex)
            {

                Console.Write(
" dgv1_RowPostPaint: "   +  ex.Message);

            }
        }

 


效果如图:

 

你可能感兴趣的:(datagridview)