loading

프로그래밍/C#

C# dataGridView 동적으로 Cell 색상 변경하기

침착곰 2021. 4. 15. 14:02
반응형

안녕하세요

C#의 dataGridView에서 동적으로 Cell 색상을 변경하는 방법에 대해서 알아보겠습니다.

저는 프로그램의 진행상태의 변경에 따라 다른 디자인으로 보이게 하는 경우 이 방법을 사용해서 구현하였습니다.

많이 사용하지는 않지만 알아두면 좋은 방법일 것 같습니다.

 

1. 프로그램cs

 dataGridView에서 CellFormatting 이벤트를 추가합니다

이벤트를 추가하고 아래처럼 구현을 합니다

if문을 사용해서 Cell의 값에 따라서 Cell 디자인을 변경해주었습니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace DataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        // 그리드 CellFormatting
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == null)
                return;
 
            // 데이터가 Red인 경우 배경색을 빨강으로 변경
            if (dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString() == "Red")
            {
                e.CellStyle.BackColor = Color.Red;
                e.CellStyle.ForeColor = Color.White;
            }
            // 데이터가 Blue인 경우 배경색을 파랑으로 변경
            else if (dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString() == "Blue")
            {
                e.CellStyle.BackColor = Color.Blue;
                e.CellStyle.ForeColor = Color.White;
            }
            // 그 외의 경우 기본 디자인으로 보여준다
            else
            {
                e.CellStyle.BackColor = Color.White;
                e.CellStyle.ForeColor = Color.Black;
            }
        }
    }
}
 
cs

 

2. 최종 소스

DataGridView.zip
0.26MB

 

3. 결과 화면

 화면처럼 Cell 값이 Red인 경우 빨강색 배경으로 Blue인 경우 파랑색 배경으로 변하는 것을 확인할 수 있습니다

 

여기까지 dataGridView에서 동적으로 Row마다 Cell의 디자인을 변경하는 방법에 대해서 알아봤습니다

C# 개발에 있어서 도움이 되셨으면 좋겠습니다

반응형
그리드형