【问题标题】:DataGridView changing cell background colorDataGridView 更改单元格背景颜色
【发布时间】:2013-04-12 21:52:50
【问题描述】:

我有以下代码:

private void dgvStatus_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dgvStatus.Rows)
    {
        row.Cells[color.Index].Style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
    }
}

我正在尝试从背景颜色列设置每个单元格的背景颜色。这不起作用颜色永远不会改变。知道为什么吗?

我一直在四处寻找,但没有发现任何有用的东西

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    只需创建一个新的DataGridViewCellStyle 对象,设置其背景颜色,然后为其指定单元格的样式:

        DataGridViewCellStyle style = new DataGridViewCellStyle();
        style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
        style.ForeColor = Color.Black;
        row.Cells[color.Index].Style = style;
    

    【讨论】:

    • 尝试了您的代码,但没有帮助。我看了你的链接,它并没有真正的帮助
    【解决方案2】:

    我终于设法让它工作了。代码如下:

    private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex != color.Index)
            return;
    
        e.CellStyle.BackColor = Color.FromArgb(int.Parse(((DataRowView)dgvStatus.Rows[e.RowIndex].DataBoundItem).Row[4].ToString()));
    }
    

    如果有人知道更好的方法,请不要犹豫发布它。我愿意接受建议

    【讨论】:

    • 我试图用Row[color.index] 替换Row[4] 它编译但在运行时我得到了一个FormatException。 color 是 datagridcolumn 的名称,它的值是 4...我不知道为什么这不起作用。有什么建议吗?
    • 看起来您正在使用本文“动态设置样式”部分中概述的方法:msdn.microsoft.com/en-us/library/1yef90x0.aspx@EJC 上一个链接的答案所指的方法。
    • 在 DataViews 中,您也可以使用列名(字符串),而不仅仅是数字索引: e.CellStyle.BackColor = Color.FromArgb(int.Parse( ((DataRowView)dgvStatus.Rows[e.RowIndex) ].DataBoundItem).Row[ "colorColumn" ].ToString() ));
    【解决方案3】:

    如果您仍然对为什么这对您一开始不起作用:

    您看不到对单元格样式所做的更改的原因是因为您在表单显示之前进行了这些更改,因此它们被忽略了。

    在此处建议的事件中更改单元格样式可以完成这项工作,但它们会被多次调用,导致您的样式更改发生的次数超出您的预期,因此效率不高。

    要解决这个问题,要么更改代码中显示表单的点之后的样式,要么订阅 Shown 事件,然后将更改放在那里(此事件的调用次数明显少于建议的其他事件) .

    【讨论】:

    • 我找不到 Shown 事件。您能否提供一个关于如何通过订阅仅调用一次且在显示 datagridview 之后才调用的偶数来更改颜色格式的小示例,以便实际显示更改?谢谢!
    • @konrad 我不知道“只调用一次”,但我最近使用了 RowsAdded,它对我来说已经足够好了,因为我只有几行,所以它没有被调用太多了。自从发布此答案以来,我还没有真正玩过这个控件,所以我不知道什么是 Shown 的好替代品
    • @konrad 你可以看看my answer
    • 很棒的回复@Ysch!
    【解决方案4】:
    dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.LightGreen;
    

    【讨论】:

    • int rowscount = dataGridView1.Rows.Count; for (int i = 0; i
    【解决方案5】:
    int rowscount = dataGridView1.Rows.Count;         
    
    for (int i = 0; i < rowscount; i++)
    {            
        if (!(dataGridView1.Rows[i].Cells[8].Value == null))
        {
            dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow;
        }
    }
    

    【讨论】:

      【解决方案6】:

      尝试以下方法(在 GridView 的 RowDataBound 方法中):

      protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
      {
          // this will only change the rows backgound not the column header 
      
          if (e.Row.RowType == DataControlRowType.DataRow)
          {
              e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col
              e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col
          }
      }
      

      【讨论】:

        【解决方案7】:

        如图所示和提到的类似:

        注意事项:请注意,在 DataGridView 控件可见后,单元格会更改其颜色(仅)。 因此,一种实用的解决方案是使用:

        VisibleChanged 事件

        如果您希望在创建新行时保持您的风格;也订阅:

        RowsAdded 事件


        以下示例:

        ///<summary> Instantiate the DataGridView Control. </summary>
        private DataGridView dgView = new DataGridView;
        
        ///<summary> Method to configure DataGridView Control. </summary>
        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;
        }
        
        ///<summary> The actual Method that will re-design (Paint) DataGridView Cells. </summary>
         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;
                 }
             }
         }
        
        ///<summary> The DataGridView VisibleChanged Event. </summary>
        private void DataGridView_VisibleChanged(object sender, EventArgs e)
        {
            DataGridView_PaintCells();
        }
        
        /// <summary> Occurrs when a new Row is Created. </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        { 
            DataGridView_PaintCells(); 
        }
        


        最后:只需调用 DataGridView_Configuration()(方法)
        即:表单加载事件。

        【讨论】:

          【解决方案8】:
          protected void grdDataListeDetay_RowDataBound(object sender, GridViewRowEventArgs e)
          {
              if (e.Row.RowType == DataControlRowType.DataRow)
              {
                  if (e.Row.Cells[3].Text != "0")
                  {
                      for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
                      {
                          e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;
                      }
                  }
              }
          }
          

          【讨论】:

          • OP 的问题是关于 DataGridView 而不是 GridView 控件。
          • 为什么是i &lt;= e.Row.Cells.Count - 1?为什么不i &lt; e.Row.Cells.Count
          【解决方案9】:

          您可以使用VisibleChanged 事件处理程序。

          private void DataGridView1_VisibleChanged(object sender, System.EventArgs e)
          {
              var grid = sender as DataGridView;
              grid.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
          }
          

          【讨论】:

            【解决方案10】:
            dataGridView1[row, col].Style.BackColor = System.Drawing.Color.Red;
            

            【讨论】:

            • 虽然此代码 sn-p 可能是解决方案,但包含解释确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
            • 并注意它是 [col, row] - 所以第一个索引用于列,第二个索引用于行
            • @TomPez,也许,顺便说一句,我现在不记得了。
            猜你喜欢
            • 2016-05-27
            • 2015-09-29
            • 2014-10-08
            • 1970-01-01
            • 2014-02-27
            • 2011-09-24
            • 2021-10-31
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多