代码之家  ›  专栏  ›  技术社区  ›  Adrian Cox

DataGridViewCheckboxCell的背景色

  •  3
  • Adrian Cox  · 技术社区  · 14 年前

    DataGridView CellFormatting 事件,如 this answer . 这适用于除 DataGridViewCheckboxColumn . 当我在该单元格内(但在复选框外)单击时,单元格背景将更改为默认的白色。

    从视觉上看,它似乎是细胞选择正在发生,尽管我尽了最大努力阻止它。我的单元格格式代码设置 SelectionBackColor BackColor . 我已使用 CellStateChanged 事件,其他列都不可选:

    private void PlayerGrid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
    {
        if (e.StateChanged == DataGridViewElementStates.Selected)
           e.Cell.Selected = false;
    }
    

    2 回复  |  直到 8 年前
        1
  •  2
  •   Adrian Cox    14 年前

    我找到了一个解决方法,将以下代码添加到 CellStateChanged 事件:

    if (e.Cell is DataGridViewCheckBoxCell)
          e.Cell.Style.BackColor = BackgroundColor(e.Cell.RowIndex);
    

    ( BackgroundColor()

    这解决了问题,但可能会导致创建额外的样式对象,从而导致较大或虚拟表的性能问题。

        2
  •  0
  •   Sting    10 年前

    我比较喜欢这种方法。它可以通过鼠标单击或制表符(例如,为了突出显示当前选定的单元格),不可知地更改任何DataGridView单元格的背景色(包括复选框)。我发现奇怪的是,其他方法没有给复选框的背景上色,因为其他类型的单元格都上色了。在我的示例中,我在CellFormatting事件中使用了这种方法,但我相信类似的语法可以在其他地方成功复制。另外,我认为这更接近于回答OPs问题,因为它与CellFormatting事件有关。

    void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
     {
    
    
    if (W.mf.dgv.CurrentCell != null && e.RowIndex==W.mf.dgv.CurrentCell.RowIndex & e.ColumnIndex==W.mf.dgv.CurrentCell.ColumnIndex)
             {
    
                     W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.YellowGreen;
    
             }
             else
             {
                     W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = W.mf.dgv.DefaultCellStyle.SelectionBackColor;
    
             }
    }
    
    推荐文章