[英]How to set a datagridview cell value color on basis of if condition
我有一個datagridview,其中有許多列和許多行的數據,我想將一些單元格的顏色設置為紅色或綠色,以便在下面的代碼中使用
正如我的代碼所示,“考試”列未讀且未進入if condition.please建議我該怎么辦。
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;
}
}
}
而不是使用==表示法,而是使用.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;
然后,您可以簡單地循環行和列
干杯! 希望能幫助到你。
這是我想要的代碼。
希望對別人有幫助。
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;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.