C# · 12月 30, 2021

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

我想要更改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) { Message@R_422_2419@.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;}