1. 방법
DataGridView에서 짝수행과 홀수행의 배경색 및 글자색을 다르게 지정하는 방법은 의외로 간단하다.
DataGridView의 속성중에 AlternatingRowsDefaultCellStyle를 설정하면 된다.
이값을 설정하지 않으면 아래의 빨강색 사각영역과 같이 기본 형식으로 출력된다.

하지만 이 속성을 설정하면 아래와 같이 출력된다.

2. 예제 소스
using CjControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using Systehttp://m.Threading.Tasks;
using Systehttp://m.Windows.Forms;
using static Systehttp://m.Windows.Forms.VisualStyles.VisualStyleElement.Button;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
CjCalendars cjCalendars = new CjCalendars();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
var col = dt.Columns.Add("CHK");
col = dt.Columns.Add("IDX");
col = dt.Columns.Add("NAME");
Random rd = new Random();
for (int i = 0; i < 10000; ++i)
{
var row = dt.Rows.Add();
row["CHK"] = rd.Next(1, 1000) % 2 == 0;
row["IDX"] = i.ToString();
row["NAME"] = $"Name{i}";
}
cjDataGridView1.SetDataSource(dt);
cjDataGridView1.Dock= DockStyle.Fill;
cjDataGridView1.DefaultCellStyle.BackColor = SystemColors.Control;
}
private void Form1_Shown(object sender, EventArgs e)
{
try
{
panel1.Controls.Add(cjCalendars);
cjCalendars.SetMonth("20250531", "20250630", true);
if (chkColorRow.Checked)
{
//짝수행 색상을 지정하기
cjDataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Red;
cjDataGridView1.DefaultCellStyle.BackColor = Color.DarkGray; // 홀수행
}
else
{
//짝수행 색상 지정을 해제하기
cjDataGridView1.AlternatingRowsDefaultCellStyle = null;
cjDataGridView1.DefaultCellStyle.BackColor = SystemColors.Control; // 모든행
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void cjDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == 0)
{
var grd = (sender as DataGridView);
var val = Convert.ToBoolean(grd.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
grd.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !val;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void chkColorRow_CheckedChanged(object sender, EventArgs e)
{
if (chkColorRow.Checked)
{
//짝수행 색상을 지정하기
cjDataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Red;
cjDataGridView1.DefaultCellStyle.BackColor = Color.DarkGray; // 홀수행
}
else
{
//짝수행 색상 지정을 해제하기
cjDataGridView1.AlternatingRowsDefaultCellStyle = null;
cjDataGridView1.DefaultCellStyle.BackColor = SystemColors.Control; // 모든행
}
}
}
}
'유용한 정보' 카테고리의 다른 글
[C#] DataGridView에서 콤보박스 컬럼을 사용하기 (2) | 2025.06.24 |
---|---|
[C#] ComboBox의 DataSource에 DataTable을 연결하여 사용하기 (0) | 2025.06.15 |
[C#] DataGridView에서 DataSource 연동하는 방법 (0) | 2025.05.24 |
[C#] 사용자 정의 달력 (2) | 2025.05.14 |
[clr] Window Forms 컨트롤 라이브러리 MFC에서 사용하기 사용 (1) | 2025.05.06 |