C#如何从外部触发DataGridView CellFormatting事件?

问题描述 投票:1回答:1

我有一个DGV,除了前N列(Item列)外,所有列中的值都有一些条件格式。前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}

Item1-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事件,以便有条件的格式更新基于新的选择。

一种方法是将update的逻辑打包到一个单独的方法中,然后在每个事件处理程序中分别调用它,我不确定该如何处理所有e.CellStyle.BackColor等。] >

有什么想法吗?

我有一个DGV,除了前N列(Item列)外,所有列中的值都有一些条件格式。前N列(类别列)具有其余......>

c# datagridview cell-formatting
1个回答
0
投票

永不失败的快速技巧是通过重置数据源来迫使数据网格重新绑定到数据源。

此主题对以下主题进行了冗长的讨论:C# refresh DataGridView when updating or inserted on another form

© www.soinside.com 2019 - 2024. All rights reserved.