DataGridView changing cell background color

后端 未结 10 1674
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 10:20

I have the following code :

private void dgvStatus_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow          


        
10条回答
  •  旧巷少年郎
    2020-11-30 10:52

    Similar as shown and mentioned:

    Notes: Take into consideration that Cells will change their color (only) after the DataGridView Control is Visible. Therefore one practical solution would be using the:

    VisibleChanged Event

    In case you wish to keep your style when creating new Rows; also subscribe the:

    RowsAdded Event


    Example bellow:

    /// Instantiate the DataGridView Control. 
    private DataGridView dgView = new DataGridView;
    
    /// Method to configure DataGridView Control. 
    private void DataGridView_Configuration()
    {
        // In this case the method just contains the VisibleChanged event subscription.
    
        dgView.VisibleChanged += DgView_VisibleChanged;
    
        // Uncomment line bellow in case you want to keep the style when creating new rows.
        // dgView.RowsAdded += DgView_RowsAdded;
    }
    
    /// The actual Method that will re-design (Paint) DataGridView Cells. 
     private void DataGridView_PaintCells()
     {
         int nrRows = dgView.Rows.Count;
         int nrColumns = dgView.Columns.Count;
         Color green = Color.LimeGreen;
    
         // Iterate over the total number of Rows
         for (int row = 0; row < nrRows; row++)
         {
             // Iterate over the total number of Columns
             for (int col = 0; col < nrColumns; col++) 
             {
                 // Paint cell location (column, row)
                 dgView[col, row].Style.BackColor = green;
             }
         }
     }
    
    /// The DataGridView VisibleChanged Event. 
    private void DataGridView_VisibleChanged(object sender, EventArgs e)
    {
        DataGridView_PaintCells();
    }
    
    ///  Occurrs when a new Row is Created. 
    /// 
    /// 
    private void DataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    { 
        DataGridView_PaintCells(); 
    }
    


    Finally: Just call the DataGridView_Configuration() (method)
    i.e: Form Load Event.

提交回复
热议问题