winform 根据DataGridView中单元格内容设置其ForeColor

DataGridView中单元格字体的颜色设置为指定的颜色。

下面代码可以对某个单元格的前景色进行设置,

DataGridview.Rows[i].Cells[j].Style.ForeColor = System.Drawing.Color.White

尝试多次后,发现代码已执行,但是前景色就是不改变。

查阅大量资料,终于发现一个有用的事件

this.gridview1.RowPrePaint += new DataGridViewRowPrePaintEventHandler(gridview1_RowPrePaint);

 void gridview1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (gridview1.Rows.Count > 0)
            {
                for (int i = 0; i < this.gridview1.Rows.Count; i++)
                {
                    this.gridview1.Rows[i].Cells[1].Style.ForeColor = ColorTranslator.FromHtml("#" + this.strfontColor[i]);
                }
            }
        }

该事件将在绘制DataGridView之前执行,必须将改变前景色的代码放到事件中,否则无效。

代码中strfontColor字符串数组存储对应的Html颜色值,利用ColorTranslator.FromHtml()将其转换为System.Drawing.Color类型。

经验证,上述事件可以根据单元格的内容,将其设置成对应的颜色。

在Windows Forms的DataGridView,没有直接提供合并单元格的功能。但是可以通过在CellPainting事件使用Graphics.DrawLine和Graphics.DrawString方法来手动实现合并单元格的效果。 下面是一个示例代码,演示如何在DataGridView合并单元格: ```csharp private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { DataGridView dgv = (DataGridView)sender; DataGridViewCell cell1 = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex]; DataGridViewCell cell2 = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex + 1]; // 判断两个相邻单元格的值是否相同,如果相同则合并单元格 if (cell1.Value != null && cell2.Value != null && cell1.Value.ToString() == cell2.Value.ToString()) { e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None; cell2.Style.BackColor = cell1.Style.BackColor; cell2.Style.ForeColor = cell1.Style.ForeColor; // 绘制合并单元格的边框 e.Graphics.DrawLine(Pens.Black, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom); // 绘制合并单元格的值 if (e.Value != null) { e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 2); } e.Handled = true; } } } ``` 在上述代码,我们通过判断相邻单元格的值是否相同来决定是否合并单元格。如果相同,则将右边单元格的边框设置为无边框,并将背景色和前景色设置为与左边单元格相同。然后使用Graphics.DrawLine方法绘制合并单元格的边框,并使用Graphics.DrawString方法绘制合并单元格的值。 请注意,上述代码只是一个示例,具体的实现方式可能会根据实际需求有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值