如何根据C#中的值更改单元格的颜色 [英] How to change a colour of a cell based on value in C#
本文介绍了如何根据C#中的值更改单元格的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使单元格的值小于100时更改颜色,但是它不会更改单元格的颜色。我可以默认整个网格的颜色,但是不适用于单个单元格。
I am trying to make a cell change colour when its value is under 100 however it does not change the color of the cell. I can default the colour of the entire grid however it is not working for individual cells. Please can someone lend a hand?
这是我到目前为止的代码:
Here is the code I have so far:
connection.Open();
var SinglesDataTable = new DataTable();
adapter.Fill(SinglesDataTable);
connection.Close();
DataColumn hourlyavg = SinglesDataTable.Columns.Add("Hourly Average", typeof(String));
for (int i = 0; i < SinglesDataTable.Rows.Count; i++)
{
object pickvalue = SinglesDataTable.Rows[i][1].ToString();
object timevalue = SinglesDataTable.Rows[i][2].ToString();
double pickval1 = Convert.ToDouble(pickvalue);
string timeS = "";
timeS = timevalue.ToString();
string timeSTrimmed = (timeS.Replace(":", ""));
string timeSTrimmedHoursMins = (timeSTrimmed.Remove(timeSTrimmed.Length - 2));
string timehourminindecimal = timeSTrimmedHoursMins.Insert(2, ".");
double timeint = Convert.ToDouble(timehourminindecimal);
if (timeint < 1)
{
timeint = Math.Ceiling(timeint);
}
else
{
timeint = timeint;
}
Convert.ToInt32(pickvalue);
var hourlyratevar = pickval1 / timeint;
double hourlyratedouble = Math.Round(hourlyratevar, 2);
int hourlyraterounded = (int)Math.Ceiling(hourlyratedouble);
SinglesDataTable.Rows[i][3] = hourlyraterounded;
string hourlyavgstring = SinglesDataTable.Rows[i][3].ToString();
double hourlyavgint = Convert.ToDouble(hourlyavgstring);
foreach (DataGridViewRow row in SinglesGridView.Rows)
if (Convert.ToInt32(row.Cells[1].Value) > 100)
{
row.DefaultCellStyle.BackColor = Color.Red;
}
SinglesGridView.DataSource = SinglesDataTable;
推荐答案
foreach (DataGridViewRow row in SinglesGridView.Rows)
if (Convert.ToInt32(row.Cells[1].Value) > 100)
row.Cells[1].Style.BackColor = Color.Red;
还有另一个选择:处理DataGridView的CellPainting事件。例如:
there is another option: handle CellPainting event of DataGridView. E.g.:
private void SinglesGridView_CellPainting(object sender,
System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 1 &&
e.RowIndex >= 0 &&
Convert.ToInt32(SinglesGridView[e.ColumnIndex, e.RowIndex].Value) > 100)
e.CellStyle.BackColor = Color.Red;
}
这篇关于如何根据C#中的值更改单元格的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文