Show row number in row header of a DataGridView

前端 未结 11 2324
野性不改
野性不改 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:35

    just enhancing above solution.. so header it self resize its width in order to accommodate lengthy string like 12345

    private void advancedDataGridView1_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
        };
        //get the size of the string
        Size textSize = TextRenderer.MeasureText(rowIdx, this.Font);
        //if header width lower then string width then resize
        if (grid.RowHeadersWidth < textSize.Width + 40)
        {
            grid.RowHeadersWidth = textSize.Width + 40;
        }
        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);
    }
    

提交回复
热议问题