Show row number in row header of a DataGridView

前端 未结 11 2366
野性不改
野性不改 2020-12-01 06:17

Is it possible to show row number in the row header of a DataGridView?

I\'m trying with this code, but it doesn\'t work:

    pri         


        
11条回答
  •  长情又很酷
    2020-12-01 06:34

    You can also draw the string dynamically inside the RowPostPaint event:

    private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
    {
        var grid = sender as DataGridView;
        var rowIdx = (e.RowIndex + 1).ToString();
    
        var centerFormat = new StringFormat() 
        { 
            // right alignment might actually make more sense for numbers
            Alignment = StringAlignment.Center, 
            LineAlignment = StringAlignment.Center
        };
    
        var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
        e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
    }
    

提交回复
热议问题