Reputation: 197
I want to change the rows forecolor and backcolor in my Dtgrdview, where Column of iRemaining != 0, by this code:
foreach(DataGridViewRow DG in dtgrdUCBuyInvoices.Rows)
if((Int64)DG.Cells["iRemaining"].Value != 0)
{
DG.DefaultCellStyle.BackColor = Color.Red;
DG.DefaultCellStyle.ForeColor = Color.White;
}
but it doesn't work and Colors don't Change !!!
how can i fix it?
Thank you very much!!
Upvotes: 0
Views: 185
Reputation: 9469
I am just guessing here possibly, but how you are getting and comparing the values is most likely failing. Also in your posted code, if the cells value is not 0, then you want to set the whole row red? Below is code that converts the string value of the cell and if it’s not zero (0) it sets that cells back color and fore color. Try the code below and see if it helps.
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;
}
}
}
Upvotes: 1
Reputation: 1175
It seems like you are trying to change the row color outside of the DataGridView
rendering.
Let's try to add your code to the RowPrePaint
event of your DataGridView
:
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;
}
}
And register it during initialization:
dtgrdUCBuyInvoices.RowPrePaint += new DataGridViewRowPrePaintEventHandler(dtgrdUCBuyInvoices_RowPrePaint);
Upvotes: 1