我有一个包含许多列和多行数据的datagridview,我想将一些单元格颜色设置为红色或绿色,以便我使用下面的代码
正如我的代码说明了专栏"考试"是不是在阅读而没有进入if条件。请建议我为我的问题做些什么。
dataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)//I have used this event
string unit = Convert.ToString(dataGridView2.Columns["exam"]);//One of my datagridview
//column name is exam and in that column cells will be unit1 or unit2 or unit3 or unit 4 or quarterly or halfyearly or yearly
if (unit == "Unit1" || unit == "Unit2" || unit == "Unit3" || unit == "Unit4")
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 7; j < dataGridView2.Rows[i].Cells.Count; j++)
{
if (Convert.ToInt32(dataGridView2.Rows[i].Cells[j].Value) < 13)
{
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Red;
}
else
{
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Green;
}
}
}
}
else
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 7; j < dataGridView2.Rows[i].Cells.Count; j++)
{
if (Convert.ToInt32(dataGridView2.Rows[i].Cells[j].Value) < 35 )
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Red;
else
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Green;
}
}
}
答案 0 :(得分:0)
而不是使用==表示法使用.Equals()
来检查它们是否相等。
if (unit.Equals("Unit 1") ||unit.Equals("Unit1") || unit.Equals("Unit2") || unit.Equals("Unit3") || unit.Equals("Unit4"))
{
//your logic
}
应用上述逻辑并使用
string data = (string)MyDataGridView[Colnum, Rownum].Value;
然后你可以简单地循环行和列
干杯!希望它有所帮助。
答案 1 :(得分:0)
这是我想要的代码。
我希望它会帮助别人..
private void dataGridView3_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
string unit = Convert.ToString(dataGridView3.Rows[i].Cells[6].Value);
if (unit == "Unit1" || unit == "Unit2" || unit == "Unit3" || unit == "Unit4")
{
for (int k = 7; k < dataGridView3.Rows[i].Cells.Count; k++)
{
int val = Convert.ToInt32(dataGridView3.Rows[i].Cells[k].Value);
if (val <= 12)
{
dataGridView3.Rows[i].Cells[k].Style.ForeColor = Color.Red;
}
else
{
dataGridView3.Rows[i].Cells[k].Style.ForeColor = Color.Green;
}
}
}
else
{
for (int j = 7; j < dataGridView3.Rows[i].Cells.Count; j++)
{
if (Convert.ToInt32(dataGridView3.Rows[i].Cells[j].Value) < 35)
{
dataGridView3.Rows[i].Cells[j].Style.ForeColor = Color.Red;
}
else
dataGridView3.Rows[i].Cells[j].Style.ForeColor = Color.Green;
}
}
}
}