here I'm going to shows a helpfull tip. Suppose if I need to assign different colors for each row in the
DataGridView
, we usually do it iterating through codebehind. There is an alternative for this instance which is directly binded
DataGridView
rows based on certain conditions.
Advantage :
Avoid loop iteraion after loading
C#
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
DataGridView grd = sender as DataGridView;
if (grd.Rows[e.RowIndex].Cells[1].Value.ToString() == "STOPED")
{
grd.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.HotPink;
}
if (grd.Rows[e.RowIndex].Cells[1].Value.ToString() == "ACTIVE")
{
grd.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGreen;
}
}
VB.Net
Private Sub dataGridView1_RowPrePaint(sender As Object, e As DataGridViewRowPrePaintEventArgs)
Dim grd As DataGridView = TryCast(sender, DataGridView)
If grd.Rows(e.RowIndex).Cells(1).Value.ToString() = "STOPED" Then
grd.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.HotPink
End If
If grd.Rows(e.RowIndex).Cells(1).Value.ToString() = "ACTIVE" Then
grd.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightGreen
End If
End Sub