【发布时间】:2021-12-30 06:07:38
【问题描述】:
我正在用 C# 创建一个简单的应用程序。我可以添加记录。我可以成功查看 DataGridview 中的记录。但我被行的颜色变化困住了。
颜色需要根据员工角色进行更改,以便于识别。员工具有以下 3 个角色之一:销售经理、软件工程师、项目经理。
软件工程师员工的颜色需要显示为红色,项目经理为蓝色,销售经理为黄色。
这是我迄今为止尝试过的 - 错误显示为无效尝试
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]是角色——如何使用if条件并根据角色改变网格单元格的颜色?
【问题讨论】:
-
这能回答你的问题吗? How to change row color in datagridview?
-
我发这篇文章之前没有解决它。我更新了上面的问题
-
你能写这个代码吗
-
int x = dataGridView1.Rows.Add...然后dataGridView1.Rows[x].DefaultCellStyle...? -
int x = int.Parse(dataGridView1.Rows.Add(read[2]).ToString()); dataGridView1.Rows[x].DefaultCellStyle.BackColor = Color.Red;仍然错误人为错误显示为无效尝试没有数据存在
标签: c#