Home > other >  DataGridview row color change based on the job role using C#
DataGridview row color change based on the job role using C#

Time:12-31

I am creating a simple application in C#. I can add the records. I can view the records in a DataGridview successfully. But I am stuck with color change of row.

The color needs to change based on the employee role for easy identification. Employee has one of 3 roles: sales manager, software engineer, project manager.

Software engineer employee's color needs to be shown as red, project managers in blue, sales manager in yellow.

This is what I tried so far - error displayed as invalid attempt

private DataTable GetDataFromDB()
            {
        
               
            }

            private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
            {
                if (dataGridView1.Columns[e.ColumnIndex].Name == "role")
                {
                    ColorRow(dataGridView1.Rows[e.RowIndex]);
                }
            }


        private void ColorAllRows() 
    {
              foreach (DataGridViewRow row in dataGridView1.Rows) {
                ColorRow(row);
              }
    }

        private void ColorRow(DataGridViewRow row)
        {
            if (row.Cells["role"].Value != null)
            {
                switch (row.Cells["role"].Value.ToString())
                {
                    case "a":
                        row.DefaultCellStyle.BackColor = Color.Yellow;
                        return;
                    case "b":
                        row.DefaultCellStyle.BackColor = Color.LightCoral;
                        return;
                    case "c":
                        row.DefaultCellStyle.BackColor = Color.LightBlue;
                        return;
                }
            }
            row.DefaultCellStyle.BackColor = Color.White;
        }

} read[2] is the role - how use if condition and change the color of the grid cell based on the role?

CodePudding user response:

You should try to avoid “manually” adding the rows to the grid as your code shows… dataGridView1.Rows.Add(read[0],read[1],read[2],read[3]); … Read the data from the query into a DataTable, then use that table as a DataSource to the DataGridView. Manually adding the rows is only going to create “more” work for you.

In reference to changing the row color based on the value in the “Role” cell, you can use the grids CellValidating event or the grids CellValueChanged event. The CellValidating event may fire more times than we need so that is the reason I prefer using the grids CellValueChanged event as shown below. This event will fire when the user changes a cells value and tries to leave the cell. Unfortunately, this event is NOT triggered when the grids DataSource is set. Therefore, we will need to implement a method that loops through the rows in the grid and color the rows “after” the grid has it’s DataSource set.

Because of this it may simplify things if we make a simple method that takes a DataGridViewRow row and checks the “Role” cells value and then colors the row accordingly. We should then be able to use that method in the CellValueChanged event AND the method we need to color the rows after the data is loaded into the grid. This straight-forward ColorRow method may look something like…

private void ColorRow(DataGridViewRow row) {
  if (row.Cells["Role"].Value != null) {
    switch (row.Cells["Role"].Value.ToString()) {
      case "Sales Manager":
        row.DefaultCellStyle.BackColor = Color.Yellow;
        return;
      case "Software Engineer":
        row.DefaultCellStyle.BackColor = Color.LightCoral;
        return;
      case "Project Manager":
        row.DefaultCellStyle.BackColor = Color.LightBlue;
        return;
    }
  }
  row.DefaultCellStyle.BackColor = Color.White;
}

If the given row’s “Role” cell is null or is not one of the targeted role types, then the row is colored White. Otherwise the row is colored according to the “role” cells value.

This should simplify both the CellValueChanged event code and the method we need to loop through the rows and color depending on the “Role” cells value. The event and method may look something like…

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
  if (dataGridView1.Columns[e.ColumnIndex].Name == "Role") {
    ColorRow(dataGridView1.Rows[e.RowIndex]);
  }
}

private void ColorAllRows() {
  foreach (DataGridViewRow row in dataGridView1.Rows) {
    ColorRow(row);
  }
}

To test this, below is a small, yet complete, example demonstrating what is described above.

DataTable GridDT;

public Form1() {
  InitializeComponent();
  dataGridView1.CellValueChanged  = new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
}

private void Form1_Load(object sender, EventArgs e) {
  GridDT = GetDataFromDB();
  dataGridView1.DataSource = GridDT;
  ColorAllRows();
}

private DataTable GetDataFromDB() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("Role", typeof(string));
  Random rand = new Random();
  string curRole = "";
  for (int i = 0; i < 20; i  ) {
    switch (rand.Next(3)) {
      case 1:
        curRole = "Software Engineer";
        break;
      case 2:
        curRole = "Project Manager";
        break;
      default:
        curRole = "Sales Manager";
        break;
    }
    dt.Rows.Add("Name "   i, curRole);
  }
  return dt;
}

The code should produce something like…

enter image description here

  •  Tags:  
  • c#
  • Related