当我的值小于100时,我试图让细胞改变颜色但是它不会改变细胞的颜色。我可以默认整个网格的颜色,但它不适用于单个单元格。请有人伸出援手吗?
这是我到目前为止的代码:
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;
答案 0 :(得分:1)
foreach (DataGridViewRow row in SinglesGridView.Rows)
if (Convert.ToInt32(row.Cells[1].Value) > 100)
row.Cells[1].Style.BackColor = Color.Red;
还有另一种选择:处理DataGridView的CellPainting事件。 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;
}