我想通过以下代码更改我的Dtgrdview中的行的前景色和背景色,其中iRemaining != 0的列:
foreach(DataGridViewRow DG in dtgrdUCBuyInvoices.Rows)
if((Int64)DG.Cells["iRemaining"].Value != 0)
{
DG.DefaultCellStyle.BackColor = Color.Red;
DG.DefaultCellStyle.ForeColor = Color.White;
}但是它不工作,颜色也不会改变!
我怎么才能修复它?
非常感谢!
发布于 2017-03-10 05:13:44
似乎您试图在DataGridView呈现之外更改行的颜色。
让我们尝试将代码添加到DataGridView的RowPrePaint事件中
private void dtgrdUCBuyInvoices_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if ((Int64)dtgrdUCBuyInvoices.Rows[e.RowIndex].Cells["iRemaining"].Value != 0)
{
dtgrdUCBuyInvoices.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
dtgrdUCBuyInvoices.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White;
}
}并在初始化过程中注册:
dtgrdUCBuyInvoices.RowPrePaint += new DataGridViewRowPrePaintEventHandler(dtgrdUCBuyInvoices_RowPrePaint);发布于 2017-03-10 05:27:56
我在这里只是猜测,但是你如何获取和比较这些值很可能是失败的。同样在您发布的代码中,如果单元格值不是0,那么您希望将整行设置为红色吗?下面的代码转换单元格的字符串值,如果不是零(0),它设置单元格的背景色和前景色。尝试下面的代码,看看它是否有帮助。
Int64 cellValue = 0;
foreach (DataGridViewRow DG in dtgrdUCBuyInvoices.Rows) {
if (!DG.IsNewRow && DG.Cells["iRemaining"].Value != null) {
Int64.TryParse(DG.Cells["iRemaining"].Value.ToString(), out cellValue);
if (cellValue != 0) {
DG.Cells["iRemaining"].Style.BackColor = Color.Red;
DG.Cells["iRemaining"].Style.ForeColor = Color.White;
}
}
}https://stackoverflow.com/questions/42705281
复制相似问题