c#如果行不为空,则更改颜色

我有一张桌子上有一些值。 如果行单元格“名称”不为空,则将背景颜色更改为紫色。

Name ID Customers Niky 1 yes // here change background to violet 2 no Donna 3 yes // here change background to violet Baka 4 no // here change background to violet 5 yes 6 no 

我试过这段代码,但我不工作,不知道为什么:

  foreach (DataGridViewRow row1 in dataGridView1.Rows) { if (row1.Cells[0].Value != null) { row1.DefaultCellStyle.BackColor = Color.Violet; } } 

如果代码在DataBindingComplete事件处理程序中,则通常放置此类的位置,如下所示附加事件或使用设计器:

 dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete); 

然后在处理程序中你有这样的东西:

 void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { foreach (DataGridViewRow row1 in dataGridView1.Rows) { if (row1.Cells.Cast().Any(c => c.Value == null || string.IsNullOrWhiteSpace(c.Value.ToString()))) { row1.DefaultCellStyle.BackColor = Color.Violet; } else { row1.DefaultCellStyle.BackColor = Color.White; } } } 

在上面的代码中,我已经将原始代码更改为现在查看所有单元格,而不仅仅是第一个单元格。


您还可以将代码放在CellFormatting事件中。

实现这一目标的一种好的(但不是高效的)方式是datagridview的事件cell-formatting 。 您可以阅读MSDN中的整个文档。 重要的是,您订阅了格式化事件,在此您可以进行格式化问题。

这样,无论用户是否正在resize,滚动任何内容,您都可以确定颜色等等。

顺便说一下:我不会在绘图事件中这样做,因为我了解到通常会破坏自动绘图逻辑;)

有关进一步的信息,有一篇关于MSDN中的cellstyles的文章,在这种情况下将是矫枉过正。 但你永远不会知道…

我不知道你把颜色代码放在哪里,但我总是在绘图部分完成它

inheritance人我根据状态给线条着色,除了第一列依赖黄色或蓝色 – 这是进行中的工作代码,应该整理

  private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex > 0) { if (dataGridView1.Rows[e.RowIndex].Cells[].Value.ToString() == "good") { e.CellStyle.BackColor = Color.PaleGreen; e.CellStyle.SelectionForeColor = Color.Black; e.CellStyle.SelectionBackColor = Color.Wheat; } if (dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString() == "warning") { e.CellStyle.BackColor = Color.LightGoldenrodYellow; e.CellStyle.SelectionForeColor = Color.Black; e.CellStyle.SelectionBackColor = Color.Wheat; } if (dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString() == "error") { e.CellStyle.BackColor = Color.Salmon; e.CellStyle.SelectionForeColor = Color.Black; e.CellStyle.SelectionBackColor = Color.Wheat; } if (e.Value.ToString() == "Yellow") { e.CellStyle.BackColor = Color.Yellow; } else if (e.Value.ToString() == "Blue") { e.CellStyle.BackColor = Color.LightBlue; } } } 

或者你可以这样做:

 foreach(DataGridViewRow r in dataGridView1.Rows) { if(!String.IsNullOrEmpty(r.Cells[0].Value.ToString())) { r.DefaultCellStyle.BackColor = Color.Violet; } } 

因此,如果一条线的所有第一个单元格都不为空,则将该行的颜色设置为紫色。

你可以在gridview的rowdatabound事件上做到这一点

你也可以使用这个用途可以通过它:

 foreach(DataGridViewRow r in dataGridView1.Rows) { if(r.Cells.Cast().Any(c => c.Value.ToString() == string.Empty)) { r.DefaultCellStyle.BackColor = Color.Violet; } }