DataGridView颜色行

时间:2017-09-29 10:16:08

标签: c# datagridview backcolor datagridviewrow

您好我正在尝试将数据网格视图行更改回颜色。我设法为一个网格执行此操作,但由于某种原因,另一个数据gridview无法正常工作。

使用Tab Control将datagridviews放置在2个不同的选项卡上。它适用于dgvTickets,但不适用于dgvFXTickets。单元索引是正确的,因为我在调试期间检查了它。任何帮助都会很棒。

        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;
            }
        }

2 个答案:

答案 0 :(得分:1)

发生这种情况是因为在控件可见之前不会更新数据绑定控件。

我在表单加载时使用此代码来防止出现此问题:

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

答案 1 :(得分:0)

在为其指定颜色代码之前,应选择标签页。

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;
        }
    }

希望这有帮助