c# DataGridView 글꼴 제어하기
DataGridViewCell.Style을 설정하여 글꼴의 색, 포매트, 모양 등을 바꿀 수 있다.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("column 0", "column 0");
dataGridView1.Rows.Add("12345");
dataGridView1.Rows[0].Cells[0].Style.ForeColor = Color.Red;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Insert(0, "abcde");
dataGridView1.Rows[0].Cells[0].Style.ForeColor = Color.DodgerBlue;
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Insert(0, "!@#$%");
dataGridView1.Rows[0].Cells[0].Style.Font = new Font(Font, FontStyle.Bold); // Font = this.Font
}
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Insert(0, new object[] { 1 });
dataGridView1.Rows[0].Cells[0].Style.Format = "0.0"; // 1.0
}
일단 셀을 특정하여 스타일을 적용하면 적용된 셀이 이동해도 스타일은 유지된다. 데이터 쏘스에 바인드를 한 경우에도 마찬가지다. 예를 들어 DataTable 가운데에 행을 삽입해도 밀려 내려가는 행들은 기존의 스타일들을 유지한 채로 이동한다.
DataGridViewRowCollection.Insert(0, 1)이라고 하면 0번 행에 행 하나를 삽입한다. 두 번째 정수는 삽입할 행의 수를 뜻하기 때문이다. 따라서 정수 값을 넣으려면 위와 같이 object 배열의 형태로 입력해야 한다.