【问题标题】:How to keep DataGridView cell forecolor when it is selected选择时如何保持DataGridView单元格前景色
【发布时间】:2020-04-30 18:01:01
【问题描述】:

我有一个DataGridView,它根据特定条件以红色和蓝色显示一些值。 However, when a row is selected, the backcolor of that row is changed (that's fine, I actually need that) but also the forecolor of all the cells in that row, which ruins everything.

这是一种只改变所选行的背景色,保持每个单元格前色与选择前一样的方法吗?

【问题讨论】:

标签: c# visual-studio datagridview


【解决方案1】:

我在这个其他答案中找到了你需要的东西:

How do I change the datagridview selected row background color?

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

【讨论】:

  • 但是执行dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Red; 会将所有选定的单元格前景色更改为红色。其中一些单元格可能必须有蓝色文本,而不是红色。我知道我可以更改选定单元格的默认前景色,但我需要的是根本不更改它...背景色可以更改,但前景色必须保持与选择单元格之前相同。
  • 当然,你可以选择前景色来匹配控件颜色,我相信叫做“控件”,这样你可以选择任何单元格,并且选择不会改变。有意义吗?
  • 我只是重新阅读了您的文字,然后您需要 color.transparent 在前色中,这种方式保持原样,只要确保您的背景色与单元格的前色有良好的对比即可。跨度>
  • 我刚试过Color.Transparent,它使前景色字面上透明,即与背景色相同的颜色,因此无法阅读。我已将表格设置为全行选择。在同一行中,我有蓝色和红色文本单元格。我很担心不可能有一个具有不同前景色单元格的选定行。
【解决方案2】:

根据您的问题,您希望在更改时保留单元格前景色

所选行的背景色。

你可以试试下面的代码。

 private void Form1_Load(object sender, EventArgs e)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name");
            table.Columns.Add("Age");
            table.Columns.Add("Id");
            table.Rows.Add("test1", 22, 1001);
            table.Rows.Add("test2", 23, 1002);
            table.Rows.Add("test3", 24, 1003);
            dataGridView1.DataSource = table;
            dataGridView1.Rows[1].Cells[1].Style.ForeColor = Color.Yellow;
            dataGridView1.Rows[1].Cells[2].Style.ForeColor = Color.Yellow;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.CurrentRow.DefaultCellStyle.SelectionBackColor = Color.Green;
            var result = dataGridView1.CurrentRow.Cells;
            foreach (DataGridViewCell item in result)
            {
                if (item.Style.ForeColor ==Color.Empty)
                {
                    item.Style.ForeColor = Color.Blue;
                }
            }

        }

测试结果:

可以看到在第二行,黄色单元格的前景色没有改变,而它的背景色已经改变了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2014-10-08
    相关资源
    最近更新 更多