c#如何检测文本框的变化? [英] c# how to detect textbox changes?
问题描述
我有一个包含大量文本框的表单我试图在表单中循环控件以检测文本框,组合框是否因为colsing形式而改变而不是工作!!
I have a form with alot of textboxes i am trying to loop controls in form to detect if textbox,combobox changes befor colsing form but not work!!
public partial class PatientFiles : Form, ILookup
{
bool NeedSaving = false;
void CheckChanges(Control.ControlCollection cc)
{
foreach (Control ctrl in cc)
{
MaskedTextBox mtxtBox = ctrl as MaskedTextBox;
TextBox txtBox = ctrl as TextBox;
ComboBox cmb = ctrl as ComboBox;
mtxtBox.TextChanged += new EventHandler(this.TextWasChanged);
txtBox.TextChanged += new EventHandler(this.TextWasChanged);
cmb.SelectedIndexChanged += new EventHandler(this.TextWasChanged);
//CheckChanges(ctrl.Controls);
}
}
//formload
private void frmPatient_Load(object sender, EventArgs e)
{
EnableNavigation();
//txtEngName.TextChanged += new EventHandler(TextWasChanged);
CheckChanges(this.Controls);
}`
public void TextWasChanged(object sender, EventArgs e)
{
NeedSaving = true;
}`
private void PatientFiles_FormClosing(object sender, FormClosingEventArgs e)
{
//NeedSaving();
// Disable Navigation On Form closing
if (NeedSaving)
{
DialogResult dt = MessageBox.Show("Save Changes", "information", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
if (dt == DialogResult.Yes)
{
SaveData();
//DisableNavigation();
}
else if (dt == DialogResult.No)
{
DisableNavigation();
NeedSaving = false;
this.Close();
}
else if (dt == DialogResult.Cancel)
e.Cancel = true;
}
}
推荐答案
MaskedTextBox mtxtBox = ctrl as MaskedTextBox;
TextBox txtBox = ctrl as TextBox;
ComboBox cmb = ctrl as ComboBox;
mtxtBox.TextChanged += new EventHandler(this.TextWasChanged);
txtBox.TextChanged += new EventHandler(this.TextWasChanged);
cmb.SelectedIndexChanged += new EventHandler(this.TextWasChanged);
一个控件不会是 MaskedTextBox
,一个 TextBox
和一个 ComboBox
同时。其中两个变量将始终为 null
,因此当您尝试添加处理程序时,您将获得 NullReferenceException
相关的已更改事件。
在尝试添加处理程序之前,更改代码以检查 null
:
A control will not be both a MaskedTextBox
, a TextBox
and a ComboBox
at the same time. Two of those variables will always be null
, so you'll get a NullReferenceException
when you try to add a handler to the relevant "changed" event.
Change your code to check for null
before trying to add the handler:
MaskedTextBox mtxtBox = ctrl as MaskedTextBox;
if (mtxtBox != null)
{
mtxtBox.TextChanged += TextWasChanged;
}
else
{
TextBox txtBox = ctrl as TextBox;
if (txtBox != null)
{
txtBox.TextChanged += TextWasChanged;
}
else
{
ComboBox cmb = ctrl as ComboBox;
if (cmb != null)
{
cmb.SelectedIndexChanged += TextWasChanged;
}
}
}
NB:供将来参考,它不起作用不是对问题的良好描述。始终包含代码抛出的任何异常的完整详细信息。
NB: For future reference, "it doesn't work" is not a good description of the problem. Always include the full details of any exception your code is throwing.
这篇关于c#如何检测文本框的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!