最近经常看到关于DataGridView的Cell背景色、合并的提问,发个源代码
源代码也在blog上发布,有什么问题可以留言
http://blog.csdn.net/Samen168/archive/2007/01/23/1491310.aspx
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add( "A ");
dt.Columns.Add( "B ");
dt.Columns.Add( "C ");
dt.Columns.Add( "D ");
dt.Rows.Add(new object[] { "A1 ", "B1 ", "C1 ", "D1 " });
dt.Rows.Add(new object[] { "A2 ", "B2 ", "C2 ", "D2 " });
dt.Rows.Add(new object[] { "A3 ", "B3 ", "C3 ", "D3 " });
this.dataGridView1.DataSource = dt;
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0 || e.RowIndex > = this.dataGridView1.Rows.Count - 1 || e.ColumnIndex == -1)
{
return;
}
// 假定需要将C列值为C3的单元格与前一单元格合并
if (e.ColumnIndex == 1 && this.dataGridView1[e.RowIndex, e.ColumnIndex + 1].Value.ToString() == "C3 ")
{
e.Handled = true;
}
if (e.ColumnIndex == 2 && e.Value.ToString() == "C3 ")
{