首页 文章

如何在DataGridView中更改单元格值时监视?

提问于
浏览
7

这是一个WinForms C#问题 .

我有一个从标准DataGridView类继承的自定义DataGridView控件 . 我想监视每当单元格添加到网格时的情况,在网格中更改单元格值 . 我不知道该怎么做 .

DataBindingCompleted事件在单元格/行/列级别无能为力 . CellValueChanged事件本身令人困惑,因为它仅在用户修改UI中的值时触发,如果从基础数据源更新值,则无助 . 听什么是正确的事件?

我知道DataGridViewCell类有一个ValueChanging事件 . 但是在自定义的DataGridView中,如何将我的事件监听器挂钩到每个单元?

谢谢您的帮助 .

2 回答

  • 1

    1,您可以在自定义DataGridView时继承DataGridView . 如果继承UserControl来自定义DataGridView,则在其他项目或应用程序中生成自定义DataGridView时无法直接获取CellValueChanged事件 .

    2,在CellValueChanged中做一些事情 .

    3,继承DataGridView工具 .

    (1)创建UserControl.Name是DataGridViewEx .

    (2)修改继承 . public partial class DataGridViewEx : UserControl ==> public partial class DataGridViewEx :DataGridView

    (3)打开DataGridViewEx.Designer.cs并屏蔽 //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; . 句子在方法InitializeComponent()中 .

  • -1

    在自定义控件中,您需要一个全局事件变量:

    public event EventHandler CustomCellValueChanged;
    

    你需要设置单元格更改事件:

    private void gvGridView_CellValueChanged(object sender, EventArgs e)
        {
            EventHandler Handler = CustomCellValueChanged;
            if (Handler != null) { Handler(this, e); };
        }
    

    然后在您的表单中,您将能够检查事件CustomCellValueChanged

相关问题