DataGridView单元格颜色改变

本文关键字:改变 颜色 单元格 DataGridView | 更新日期: 2023-09-27 18:14:45

我有一个测试程序,构建一个数据表(26行乘6 cols)作为DataGridView的数据源。
数据网格可以通过选择单元格并从3个NumUpDown控件之一输入值来编辑。
每个控件都有特定的颜色。为了保存信息,我将表保存在用户设置中。
我将每个单元格的颜色信息保存在额外的表格单元格中。
问题:当我显示数据网格时,它从表中读取OK值,但是应该根据额外的单元格信息以编程方式添加的单元格颜色没有显示。
(我可以在诊断中看到单元格得到了正确的颜色,但它没有显示在数据网格中。
看起来datagird有一些颜色覆盖(?)。
附件是完整的工作代码。
查看代码中的更多信息。
有没有人可以运行这个并找到为什么颜色没有显示在数据网格中?谢谢。

using System;
using System.Data;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Windows.Forms;
//This is a test program to do the following:
//1. Build an empty data table of 26 rows by 6 columns.
//2. The Table is bind (as DataSource) to a DataGridView.
//3. The DataGrid Colomns 0-3 can be filled with decimals by one of 3 NumericUpDown  controls.
//3. For each cell in cols 0-2 there is one in cols 3-5 that holds info which NumUpDn  was used.
//4. Each NumUpDn has specific color. The corresponding cells have the same backcolor.
//5. When the program starts, it builds the table from the Settings, and displays the  table in the datagrid.
//6. The cells in cols 0-2 are supposed to get the colors ad indicated in cols 3-5, but   they do not.
//To run, make a WinForm with a datagrid 'fareGrid' and 3 NumUpDn controls with background colors.  

namespace DataGridViewTest
{
public partial class Form1 : Form
{
    DataTable fareTable = new DataTable();
    int rowIndex;
    int colIndex;
    public Form1()
    {
        InitializeComponent();
        buildFareTable("fareTable");
        // Load the table (if exists)
        if (Properties.Settings.Default.fareTable != null)
            fareTable = Properties.Settings.Default.fareTable;
        paintFareTableCells(fareTable);
    }
    //Build the initial data table of 26R X 6C
    //Columns 3-5 are used to hold the color information of cols 0-2
    public void buildFareTable(string fareTableName)
    {
        fareTable.TableName = fareTableName;
        fareTable.Columns.Add("Weekday", typeof(Decimal));
        fareTable.Columns.Add("HalfDay", typeof(Decimal));
        fareTable.Columns.Add("Weekend", typeof(Decimal));
        //Adding 3 indexing columns that will hold the tables cell group
        fareTable.Columns.Add("IWeekday", typeof(String));
        fareTable.Columns.Add("IHalfDay", typeof(String));
        fareTable.Columns.Add("Iweekend", typeof(String));
        for (rowIndex = 0; rowIndex < 26; rowIndex++)
        {
            fareTable.Rows.Add();
        }
    }
    public void paintFareTableCells(DataTable fareTable)
    {
        fareDataGrid.DataSource = fareTable;
        for (rowIndex = 0; rowIndex < 26; rowIndex++)
        {
            for (colIndex = 0; colIndex < 3; colIndex++)
            {
                switch (fareTable.Rows[rowIndex][colIndex + 3].ToString())   //Check the color index columns 3-5
                {
                    case "low": fareDataGrid[colIndex, rowIndex].Style.BackColor = Color.Green;  
                        break;
                    case "med": fareDataGrid[colIndex, rowIndex].Style.BackColor = Color.Yellow; 
                        break;
                    case "high": fareDataGrid[colIndex, rowIndex].Style.BackColor = Color.Red;  
                        break;
                    default:
                        break;
                }
                // Diagnostics: Check cell's color. At this point, Colors are OK!  
                Color color = fareDataGrid[colIndex, rowIndex].Style.BackColor;  
            }
        }
    }
   //Update the cells by 3 NumUpDn controls.
    private void numericUpDownFareHigh_ValueChanged(object sender, EventArgs e)
    {
        editFareTableCells(sender);
    }
    private void numericUpDownFareMed_ValueChanged(object sender, EventArgs e)
    {
        editFareTableCells(sender);
    }
    private void numericUpDownFareLow_ValueChanged(object sender, EventArgs e)
    {
        editFareTableCells(sender);
    }
    public void editFareTableCells(Object sender)
    {
        foreach (DataGridViewCell cell in fareDataGrid.SelectedCells)
        {
            if (cell.ColumnIndex < 3)
            {
                cell.Value = ((NumericUpDown)sender).Value;
                cell.Style.BackColor = ((NumericUpDown)sender).BackColor;
                fareDataGrid[cell.ColumnIndex + 3, cell.RowIndex].Value = ((NumericUpDown)sender).Tag;   //Uses cols 3-5 to hold cost level info.
            }
        }
    }
    //Use settings to preserve the data
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        Properties.Settings.Default.fareTable = this.fareTable;
        Properties.Settings.Default.Save();
    }
}
}

DataGridView单元格颜色改变

变色代码必须在事件处理程序中;具体来说,是DataBindingComplete事件处理程序。我重写了你的代码如下:

public void paintFareTableCells(DataTable fareTable)
{
    fareDataGrid.DataSource = fareTable;
}
void fareDataGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    for (rowIndex = 0; rowIndex < 26; rowIndex++)
    {
        for (colIndex = 0; colIndex < 3; colIndex++)
        {
            switch (fareTable.Rows[rowIndex][colIndex + 3].ToString())   //Check the color index columns 3-5
            {
                case "low":
                    fareDataGrid[colIndex, rowIndex].Style.BackColor = Color.Green;
                    break;
                case "med":
                    fareDataGrid[colIndex, rowIndex].Style.BackColor = Color.Yellow;
                    break;
                case "high":
                    fareDataGrid[colIndex, rowIndex].Style.BackColor = Color.Red;
                    break;
                default:
                    break;
            }
            // Diagnostics: Check cell's color. At this point, Colors are OK!  
            Color color = fareDataGrid[colIndex, rowIndex].Style.BackColor;
        }
    }
}

单元格现在根据需要的值改变颜色。

顺便说一下,不要忘记在构造函数中订阅事件处理程序:
fareDataGrid.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(fareDataGrid_DataBindingComplete);

在您的paintFareTableCells中,很可能case语句正在传递到default,因此没有设置任何值。使用断点确认这一点,并相应地修改列索引。

不幸的是,我不知道为什么你的细胞没有被画成他们应该是,但我最好的猜测是你试图改变他们的属性之前,他们处理他们的油漆事件的事实。就像Joe Sisk建议的那样,我设法用事件改变细胞的颜色,对我来说效果很好。我希望这对你有所帮助。不同之处在于我使用了CellPainting事件,这里是我所做的简短版本,我希望它能帮助你自己找出剩下的…

    private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.Value != null) // if condition is met, this cell will be painted
        {
            e.CellStyle.BackColor = Color.Black; // i used black color, feel free to replace it :)
        }
    }   

我希望这对你有用?