DataGridView CellMouseMove Row backcolor更改

时间:2016-12-13 17:15:15

标签: c# datagridview

我正在使用此代码:

Sub MakroBisect()
Dim StartTime As Date
Dim EndTime As Date


StartTime = Timer

    wbAdjust "$P$4:$BC$8"
    wbBest "C32", "Minimize"
    wbConstraint "P9:BB9", "=", "P11:BB11", "P10:BB10"
    wbConstraint "J3:J7", ">=", "L3:L7", "K3:K7"
    WBBIN "Plantusage", "BC4:BC8"
    wbSolve

Range("M3:M7").ClearContents
Range("H27") = 1000
Range("H28") = 100000


Dim rng As Range, cell As Range

Set rng = Range("D3:D7")

For Each cell In rng

    Do
    If cell.Offset(1, 51).Value = 1 Then

        Range("H27") = cell.Value

    Else
        Range("H28") = cell.Value

    End If

        cell.Value = Range("H29").Value

        wbAdjust "$P$4:$BC$8"
        wbBest "C32", "Minimize"
        wbConstraint "P9:BB9", "=", "P11:BB11", "P10:BB10"
        wbConstraint "J3:J7", ">=", "L3:L7", "K3:K7"
        WBBIN "Plantusage", "BC4:BC8"
        wbSolve

    Loop Until Range("H31") = 1

    Range("H27").Value = 0
    Range("H28").Value = 100000

    'Copying cell Value, when Solver solution switched in certain cell depending if it before was 1 or 0
    cell.Copy cell.Offset(, 9)
    'Copying start value back into cell after solver loop
    cell.Offset(, -1).Copy cell

        wbAdjust "$P$4:$BC$8"
        wbBest "C32", "Minimize"
        wbConstraint "P9:BB9", "=", "P11:BB11", "P10:BB10"
        wbConstraint "J3:J7", ">=", "L3:L7", "K3:K7"
        WBBIN "Plantusage", "BC4:BC8"
        wbSolve

Next cell


EndTime = Timer
Range("H8").Value = Format(EndTime - StartTime, "0.0")


End Sub

仅适用于特定细胞。如果我想改变整行的颜色怎么办?

2 个答案:

答案 0 :(得分:0)

您可以循环遍历所有行和单元格,并将它们的BackColor设置为颜色

//Loop through all of the rows
for( int i = 0; i < dataGridView1.Rows.Count; i++ ) {

    //Set a variable called row for quick access to the current row
    var row = dataGridView1.Rows[i];

    //Loop through all the cells in row
    for( int x = 0; x < row.Cells.Count; x++ ) {

        //Set the cell to a variable for quick access
        var cell = row.Cells[x];

        //Set the back color of the cell to your desired color
        cell.Style.BackColor = Color.Blue;
    }
}

这将确定行数,然后循环遍历它们,并在每一行中确定单元格的数量并循环遍历它们,然后将该特定单元格的背面颜色设置为所需的颜色。

答案 1 :(得分:0)

您可以使用以下内容设置整行:

dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue;

当鼠标移过它时,这将改变每一行的颜色,但这不会改变它...当你的鼠标滚过每个单元格时,每一行都会改变颜色而不会改变回默认的白色。小鼠离开细胞。下面是一些代码,当鼠标离开单元格时,颜色会变回白色。您必须检查其他事件,例如用户在单元格中输入文本时,因为当您将鼠标移开时,单元格将保持更改的颜色。

private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
      dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue;
}

private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
  if (e.RowIndex >= 0)
    dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
}