如何防止值更改事件触发.NET中的表单初始化? [英] How to prevent value changed events from firing on form initialization in .NET?

查看:73
本文介绍了如何防止值更改事件触发.NET中的表单初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个带有几个单选按钮和一个复选框的简单.NET表单。

Consider a simple .NET form with a couple of radio buttons and a checkbox.

每个单选按钮都有一个CheckedChanged处理程序设置,该设置可以根据以下内容执行某些操作

Each of the radio buttons has a CheckedChanged handler setup that performs some action based on the state of the checkbox.

我的问题是,当我在要检查的默认单选按钮上初始化(从设计器属性窗口中)时,为该单选激发了CheckedChanged事件按钮,但Checkbox尚未初始化,因此我得到了空指针异常或在处理程序中使用了错误的值。无论哪种方式,我都不希望运行该处理程序代码,除非用户在表单加载后选择了一个单选按钮。

My problem is, when I initialize on the default radiobutton to be checked (from the designer properties window) the CheckedChanged event is fired for that radio button, but the Checkbox hasn't been initialized yet so I either get a null pointer exception or the wrong value is used in the handler. Either way, I don't want that handler code to be run unless the user picks a radio button after the form has been loaded.

我目前不解决此问题初始化单选按钮,但最终我需要设置默认值,最好的地方是设计师。我还可以添加一个布尔字段,直到表单完全加载后才将其设置为true;如果为false,则不处理事件,但这是一个肮脏的hack。

I currently get around this by not initializing the radio button, but I need to set that default eventually and the best place is from the designer. I also can add a boolean field that's not set to true until the form is fully loaded and not process the events if that is false, but it's a dirty hack.

什么我该怎么做以防止该处理程序运行其代码?

What can I do to prevent that handler from running its code?

推荐答案

我还可以放置一个未设置为true的布尔字段直到表单完全加载,如果错误则不处理事件,但这是一个肮脏的hack。

"I also can put a boolean field that's not set to true until the form is fully loaded and not process the events if that is false, but it's a dirty hack."

这也是一种简便且最佳的方法!

It's also the easist and best way to do it!

可以说.NET提供了一种巧妙的方法来关闭和关闭所有事件处理程序,直到加载表单为止。甚至只是您正在处理的那些。禁用要启用的功能还是禁用不想要的功能仍然不够灵活。表单设置经常发生,并且您希望事件触发。此外,如果 no 事件触发,则表单将无法正确构建。

Lets say .NET provides a neat way to turn an and off all the event handlers until the form is loaded. Even just the ones YOU are handling. It would still not be sufficiently flexible to disable what you wanted to enable but disable what you didn't. Often form setups happen and you want the events to fire. Also the form won't build right if no events fire.

这篇关于如何防止值更改事件触发.NET中的表单初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆