1

我有一个 DGV,它对除前 N 列(项目列)之外的所有列中的值都有一些条件格式。前 N 列(类别列)具有表其余部分的参考值。像这样的东西:

Category1 Category2 Item1 Item2 Item3 Item4
1         2         1     2     1     2
56        57        57    56    56    56

我还有一个字典,它设置所有列的标题与参考列的标题的对应关系。

{Item1, Category1}
{Item2, Category1}
{Item3, Category1}
{Item4, Category2}

Items1-4 的每个单元格都与 CellFormatting 事件处理程序中的相应类别(使用字典)进行比较,然后如果匹配,则将单元格着色为绿色,否则为红色。

换句话说,在 CellFormatting 事件的处理程序中,我使用字典来检查特定列应该从 N 参考列中具有哪些值。

现在我有一个完全独立的控件(另一个带有组合框的 DGV),它允许用户更改该字典(切换每个项目所属的类别)。更改该字典时如何手动引发 CellFormatting 事件?

这是我的单元格格式事件处理程序:

        private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            try
            {

                if (e.ColumnIndex > N_of_ReferenceColumns)
                {

                    if (e.Value.ToString() == this.dataGridView.Rows[e.RowIndex].Cells[dataGridView.Columns[convertItemToCategory(dataGridView.Columns[e.ColumnIndex].Name)].Index].Value.ToString())
                    {

                        e.CellStyle.BackColor = Color.Green;
                        e.CellStyle.SelectionBackColor = Color.DarkGreen;
                    }
                    else
                    {
                        e.CellStyle.BackColor = Color.Red;
                        e.CellStyle.SelectionBackColor = Color.DarkRed;
                    }
                }
            }
            catch
            { }

        }

这是我在组合框中更改每个项目的类别值的处理程序:

        private void DictionarydataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            UpdateDictionary(DictionarydataGridView.Rows[e.RowIndex].Cells[1].Value.ToString(), DictionarydataGridView.Rows[e.RowIndex].Cells[0].Value.ToString());
        }

这就是我更新字典以及在条件格式逻辑中使用它的方式:

    public static IDictionary<string, string> Dictionary = new Dictionary<string, string>();

        public void UpdateDictionary(string key, string value)
        {
            Dictionary[key] = value;

        }
        public static string convertItemToCategory(string key)
        {
            string value = "";
            if (Dictionary.TryGetValue(key.ToUpper(), out value))
            {
                return value;
            }
            else
            {
                return key.ToUpper();
            }

        }

我需要做的是在更新 Dictionary 时,同时引发 CellFormatting 事件,以便根据新选择更新条件格式。

一种方法是将更新逻辑打包到一个单独的方法中,然后从每个事件处理程序中单独调用它,我不确定如何处理所有 e.CellStyle.BackColor 等等......

有任何想法吗?

4

1 回答 1

2

一个永不失败的快速破解方法是通过重置数据源来强制数据网格重新绑定到数据源。

该线程对该主题进行了冗长的讨论:C# refresh DataGridView when updated or insert on another form

您可以在表单上放置一个辅助方法:

public void Refresh()
{
    datagridview1.DataSource = datagridview1.DataSource; // should re-evaluate all logic related to data bindings
    datagridview1.Refresh(); // forces the control to repaint
}

这可能是最密集的解决方案,但它应该可以完成这项工作。

于 2020-01-11T04:00:13.127 回答