c# – DataGridView行的背景颜色不变

前端之家收集整理的这篇文章主要介绍了c# – DataGridView行的背景颜色不变前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_0@
我想要更改DGV的行的背景颜色基于特定的条件,即使在 Windows窗体中的负载.但是,我看不到任何DGV行的颜色有任何改变.有人可以告诉我如何解决这个问题?
private void frmSecondaryPumps_Load(object sender,EventArgs e)
{
            try
            {
                DataTable dt = DeviceData.BindData("SECONDARY_PUMPS".ToUpper());
                dataGridView1.DataSource = dt;

                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    foreach (DataGridViewColumn column in dataGridView1.Columns)
                    {
                        if (row.Cells[column.Name] != null)
                        {
                            if (row.Cells[column.Name].Value.ToString() == "ON")
                                row.DefaultCellStyle.BackColor = System.Drawing.Color.Green;

                            if (row.Cells[column.Name].Value.ToString() == "OFF")
                                row.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
                        }
                    }
                }

                dataGridView1.Refresh();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

解决方法

我认为最好的办法是在DataGridView的CellFormatting事件中设置BackColor,这些都是这些.
private void grid1_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
{
    DataGridViewRow row = grid1.Rows[e.RowIndex];// get you required index
    // check the cell value under your specific column and then you can toggle your colors
    row.DefaultCellStyle.BackColor = Color.Green;
}

猜你在找的C#相关文章