简体   繁体   English

基于作业角色的 DataGridview 行颜色更改使用 C#

[英]DataGridview row color change based on the job role using C#

I am creating a simple application in C#.我正在 C# 中创建一个简单的应用程序。 I can add the records.我可以添加记录。 I can view the records in a DataGridview successfully.我可以成功查看 DataGridview 中的记录。 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这是我迄今为止尝试过的 - 错误显示为无效尝试

public void Load()
{
     SqlDataAdapter ada1 = new SqlDataAdapter("select * from contact", con);
        DataTable dt = new DataTable();
        ada1.Fill(dt);
        con.Open();

        
        dataGridView1.Rows.Clear();

        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(curRole);
        }
        return dt;
    }
}

read[2] is the role - how use if condition and change the color of the grid cell based on the role? read[2]是角色 - 如何使用 if 条件并根据角色更改网格单元格的颜色?

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]);您应该尽量避免“手动”将行添加到网格中,如代码所示…… 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 . ... 将查询中的数据读取到DataTable ,然后将该表用作DataGridViewDataSource 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.关于根据“角色”单元格中的值更改行颜色,您可以使用网格CellValidating事件或网格CellValueChanged事件。 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. CellValidating事件的触发次数可能比我们需要的多,因此我更喜欢使用网格CellValueChanged事件,如下所示。 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.不幸的是,设置网格DataSource时不会触发此事件。 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.因此,我们需要实现一个方法,循环遍历网格中的行,并在网格设置了DataSource之后为行着色。

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.因此,如果我们创建一个简单的方法,该方法采用DataGridViewRow行并检查“Role”单元格值,然后相应地检查该行,则可能会简化事情。 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.然后,我们应该能够在CellValueChanged事件中使用该方法以及在将数据加载到网格后为行着色所需的方法。 This straight-forward ColorRow method may look something like…这种直截了当的ColorRow方法可能看起来像……

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.如果给定行的“角色”单元格是null或不是目标角色类型之一,则该行颜色为白色。 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.这应该简化CellValueChanged事件代码和我们需要根据“角色”单元格值循环行和颜色的方法。 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…代码应该产生类似...

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM