Mark Fenech
Mark Fenech

Reputation: 3

DataGridView color rows

Hi I am trying to change the data grid view rows back color. I managed to do this for one grid but for some reason another data gridview is not working.

The datagridviews are placed on a 2 different tabs using Tab Control. It works perfect for dgvTickets but is not working for dgvFXTickets. The cell index is correct as I checked it during debugging. Any help would be great.

        dgvFXTickets.AutoGenerateColumns = true;
        dgvFXTickets.DataSource = new DataAccess.FinanceData().getFXTicketsByDate(dateTimePicker1.Value).ToList();

        dgvTickets.AutoGenerateColumns = true;
        dgvTickets.DataSource = new DataAccess.FinanceData().getTicketsByDate(dateTimePicker1.Value).ToList(); 


        foreach (DataGridViewRow r in dgvTickets.Rows)
        {
            if (r.Cells[8].Value.ToString() == "Completed")
            {
                r.DefaultCellStyle.BackColor = Color.LightGreen;
            }

            else if (r.Cells[8].Value.ToString() == "Cancelled")
            {
                r.DefaultCellStyle.BackColor = Color.LightPink;
            }
        }

        foreach (DataGridViewRow rFX in dgvFXTickets.Rows)
        {
            if (rFX.Cells[12].Value.ToString() == "Completed")
            {
                rFX.DefaultCellStyle.BackColor = Color.LightGreen;
            }

            else if (rFX.Cells[12].Value.ToString() == "Cancelled")
            {
                rFX.DefaultCellStyle.BackColor = Color.LightPink;
            }
        }

Upvotes: 0

Views: 82

Answers (2)

tezzo
tezzo

Reputation: 11105

This happened because a databound control is not updated until the control is made visible.

I use this code on form load to prevent this problem:

Private Sub frmForm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    For Each tabPage As TabPage In Me.tabTabControl1.TabPages
        tabPage.Show()
    Next tabPage

End Sub

Upvotes: 1

christo issac
christo issac

Reputation: 460

The tab page should be selected before assigning color codes on it.

tabControl1.SelectedTab = 0; //select first tab page    
foreach (DataGridViewRow r in dgvTickets.Rows)
{
        if (r.Cells[8].Value.ToString() == "Completed")
        {
            r.DefaultCellStyle.BackColor = Color.LightGreen;
        }

        else if (r.Cells[8].Value.ToString() == "Cancelled")
        {
            r.DefaultCellStyle.BackColor = Color.LightPink;
        }
    }

tabControl1.SelectedTab = 1   //select second tab 
foreach (DataGridViewRow rFX in dgvFXTickets.Rows)
    {
        if (rFX.Cells[12].Value.ToString() == "Completed")
        {
            rFX.DefaultCellStyle.BackColor = Color.LightGreen;
        }

        else if (rFX.Cells[12].Value.ToString() == "Cancelled")
        {
            rFX.DefaultCellStyle.BackColor = Color.LightPink;
        }
    }

Hope this helps

Upvotes: 0

Related Questions