c# DataGridView 잔기술들 5

칼럼 폭 자동 조절

dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.WindowText;

셀 단위로 포맷하기

출력 포맷을 설정할 때에는 주로 칼럼 단위로 하지만 간혹 셀 단위로 해야 할 때도 있다. 아래와 같이 한다.

dataGridView1.Columns.Add("column 0", "column 0");
dataGridView1.Columns.Add("column 1", "column 1");
dataGridView1.Rows.Add("int", 1); // 1 -> default format
dataGridView1.Rows.Add("double", 1);
dataGridView1.Rows[1].Cells[1].Style.Format = "0.0"; // 1.0

셀 단위로 색 바꾸기

위의 예제에서 Style.Format을 Style.Backcolor로 바꾸면 된다. 동적으로 바꾸고 싶으면 아래와 같이 DataGridView.CellPainting 이벤트를 쓰면 된다. 이 이벤트가 작동할 때 e.ColumnIndex와 e.RowIndex는 모두 -1 즉 헤더부터 시작하므로 셀을 제어할 때에는 이들 인덱스가 0보다 클 때에만 작동하게 if를 써야 한다. 그러지 않으면 out of range index 오류가 발생한다.

private void Form1_Load(object sender, EventArgs e) 
{ 
    dataGridView1.Columns.Add("0", "0"); 
    dataGridView1.Rows.Add("0"); 
    dataGridView1.Rows.Add("1"); 
} 
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.RowIndex == 0) 
    { 
        dataGridView1.Rows[e.RowIndex].Cells[0].Style.BackColor = Color.Red; 
    } 
}

DefaultCellStyle 설정하기

셀의 기본 스타일은 DataGridView.DefaultCellStyle, DataGridView.RowDefaultCellStyle, DataGridView1.RowTemplate.DefaultCellStyle 이렇게 세 군데에서 설정할 수 있다. 복잡하다. 위의 설정 모두를 다르게 한 때 서로의 우열 관계가 문제된다. DataGridView.DefaultCellStyle은 제일 전반적인 설정이다. 헤더들은 따로 설정하므로 헤더들에는 적용되지 않는다. 특이한 건 Alignment가 MiddleLeft로 기본 설정되어 있어서 NotSet으로 바꾸고 다시 들어가 보면 MiddleLeft로 바뀌어 있다. DataGridView.RowDefaultCellStyle은 말 그대로 행 단위 설정이다. DataGridView.DefaultCellStyle을 상속하며 이것에 우선한다. 모든 행들의 셀에 작용하므로 효과는 DataGridView.DefaultCellStyle을 설정하는 것과 같다. 단지 이들을 서로 다르게 한 경우 앞에 설명한 것처럼 override하고 나타난다. DataGridView1.RowTemplate.DefaultCellStyle의 설정은 가장 우선한다. 행의 높이를 바꿀 때 말고는 쓸 일이 거의 없다.