【问题标题】:How do I change the datagridview selected row background color?如何更改 datagridview 选定行的背景颜色?
【发布时间】:2011-03-11 20:12:35
【问题描述】:

如何在 C# windows 应用程序中更改 datagridview 选定行的背景颜色?

【问题讨论】:

  • 您需要为问题添加更多细节,也许发布一些代码以及您尝试过的内容以及失败的内容。您的问题目前无法回答。

标签: c# winforms datagridview


【解决方案1】:

拜托,必须有一个简单的解决方案,终于找到了。

dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Blue;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Red;

这对我有用,没有复杂的代码,没有事件处理。我以前做过,但不记得了,所以认为发布它会帮助其他人和我将来:)

【讨论】:

    【解决方案2】:

    DataGridView 上有一个DefaultCellStyle,里面有SelectionBackColorSelectionForeColor 属性。

    DataGridView 采用了样式继承的思想,以防你发现你选择的样式没有被应用:

    http://msdn.microsoft.com/en-us/library/1yef90x0.aspx

    【讨论】:

      【解决方案3】:

      利用DataGridViewCell 的事件CellEnterCellLeave 你可以尝试这样的事情:

      private void foobarDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
      {
        DataGridViewCellStyle fooCellStyle = new DataGridViewCellStyle();
        fooCellStyle.BackColor = System.Drawing.Color.LightYellow;
        this.VariableFinderDataGridView.CurrentCell.Style.ApplyStyle(fooCellStyle);
      }
      
      private void foobarFinderDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
      {
        DataGridViewCellStyle barCellStyle = new DataGridViewCellStyle();
        barCellStyle.BackColor = System.Drawing.Color.White;
        this.VariableFinderDataGridView.CurrentCell.Style.ApplyStyle(barCellStyle);
      }
      

      【讨论】:

      • 如果选择前的行颜色不是白色怎么办?
      • 我的意思是这只是一个简单的示例来说明这个概念——你只需创建一个辅助方法来检索你需要在那里切换的任何颜色。
      【解决方案4】:

      这是您可以复制和粘贴的简单且有效的版本:

      private void dataGridView1_SelectionChanged(object sender, EventArgs e)
      {
          (sender as DataGridView).CurrentRow.DefaultCellStyle.SelectionBackColor = Color.Green;
      }
      

      【讨论】:

      • 这是我真正想要的,谢谢!
      【解决方案5】:

      这是我的代码

      private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
      {
      dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
      dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
      }
      

      【讨论】:

      • 好一个亚当!我从来不知道它存在!
      【解决方案6】:

      颜色也可以在“DataGridView”的设计器中更改

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-10
        相关资源
        最近更新 更多