加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:53:35 所属栏目:百科 来源:网络整理
导读:我想要更改DGV的行的背景颜色基于特定的条件,即使在 Windows窗体中的负载.但是,我看不到任何DGV行的颜色有任何改变.有人可以告诉我如何解决这个问题? private void frmSecondaryPumps_Load(object sender,EventArgs e){ try { DataTable dt = DeviceData.Bi
我想要更改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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读