[C#] DataGridView 에서 로우 헤더에 넘버 추가하는 방법.

DataGridView에서 로우 헤더에 로우 넘버를 추가하는 방법은 RowPostPaint 이벤트를 사용하여 구현할 수 있습니다.

로우 헤더에 넘버 추가

다음 코드에서는 각 행의 번호를 로우 헤더에 출력하는 방식으로 작성한 예시입니다. 코드에서 핵심 포인트들을 하나씩 살펴보겠습니다.

private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();
    var centerFormat = new StringFormat()
    {
        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);
}

코드 설명

  1. dataGridView_RowPostPaint 메서드:
    • 이 메서드는 RowPostPaint 이벤트 핸들러로, DataGridView에서 행이 그려진 후에 호출됩니다.
    • 매개변수 sender는 이벤트가 발생한 DataGridView를 나타내며, e는 그려진 행에 대한 정보(DataGridViewRowPostPaintEventArgs)를 포함하고 있습니다.
  2. 행 번호 계산:
    var rowIdx = (e.RowIndex + 1).ToString();
    
    • e.RowIndex는 현재 행의 인덱스(0부터 시작)를 나타내므로, 1을 더하여 1부터 시작하는 행 번호를 얻습니다.
    • 이를 문자열로 변환하여 출력 준비를 합니다.
  3. 문자열 포맷 지정:
    var centerFormat = new StringFormat()
    {
        Alignment = StringAlignment.Center,
        LineAlignment = StringAlignment.Center
    };
    
    • StringFormat 객체를 사용하여 텍스트의 정렬 방식을 지정합니다.
    • 가로 및 세로 방향 모두 가운데 정렬을 지정합니다.
  4. 헤더 영역 지정:
    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    
    • 각 행의 헤더 영역의 크기를 Rectangle 객체로 지정합니다. 이 영역은 텍스트를 그릴 영역을 나타냅니다.
    • e.RowBounds.Lefte.RowBounds.Top은 각 행의 위치를 나타내며, grid.RowHeadersWidth는 로우 헤더의 너비, e.RowBounds.Height는 행의 높이를 나타냅니다.
  5. 그래픽으로 그리기:
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
    
    • e.Graphics.DrawString 메서드를 사용하여 지정한 영역(headerBounds)에 텍스트(rowIdx)를 그립니다.
    • this.Font은 현재 폼의 폰트를 사용하고, SystemBrushes.ControlText를 사용하여 시스템 기본 텍스트 색상으로 출력합니다.
    • 마지막 매개변수로 centerFormat을 전달하여 가운데 정렬된 텍스트를 표시합니다.

추가적인 고려 사항

  • 폰트 크기 조정: 만약 로우 헤더의 폰트 크기가 작거나 크면, this.Font 대신 new Font("폰트 이름", 크기)로 폰트를 지정할 수 있습니다.
  • 정렬 방식 변경: 행 번호가 길어질 경우(예: 1000 이상의 큰 숫자) 숫자를 우측 정렬하는 것이 더 자연스러울 수 있습니다. 그런 경우에는 centerFormat.Alignment = StringAlignment.Far로 변경하면 됩니다.
이전최근
댓글 쓰기
가져가실 때, 출처 표시 부탁드려요! 감사합니다. 💗