如何将focus()赋予错误提供程序在C#Windows应用程序中命中的第一个控件?
在一个表单中,我有12个控件。(所有控件都应填充一些数据)如果用户希望保存,则不向控件输入任何文本,我将显示所有控件的ErrorProviders。请输入数据。我正在显示代码如何将focus()赋予错误提供程序在C#Windows应用程序中命中的第一个控件?,c#,winforms,focus,controls,errorprovider,C#,Winforms,Focus,Controls,Errorprovider,在一个表单中,我有12个控件。(所有控件都应填充一些数据)如果用户希望保存,则不向控件输入任何文本,我将显示所有控件的ErrorProviders。请输入数据。我正在显示代码 public ErrorProvider mProvider; public void SetError(Control ctl, string text) { if (string.IsNullOrEmpty(text)) mErrors.Remove(ctl); else if (!mErrors.Co
public ErrorProvider mProvider;
public void SetError(Control ctl, string text)
{
if (string.IsNullOrEmpty(text)) mErrors.Remove(ctl);
else if (!mErrors.Contains(ctl)) mErrors.Add(ctl);
mProvider.SetError(ctl, text);
ctl.Focus();
}
如果控件有空数据,我将把控件信息和错误文本传递给SetError
方法。我想将focus()
设置为点击此SetError
方法的第一个控件
单击按钮时,我调用此方法
Public void Isinptvlid
{
if (textBox1.Text.Length == 0)
{
obj.SetError(textBox1, "textBox1 cann't be Zero Length");
}
if (textBox2.Text.Length == 0)
{
obj.SetError(textBox2, "textBox2 cann't be Zero Length");
}
if (textBox3.Text.Length == 0)
{
obj.SetError(textBox3, "textBox3 cann't be Zero Length");
}
if (textBox4.Text.Length == 0)
{
obj.SetError(textBox4, "textBox4 cann't be Zero Length");
}
if (textBox5.Text.Length == 0)
{
obj.SetError(textBox5, "textBox5 cann't be Zero Length");
}
if (textBox6.Text.Length == 0)
{
errprvBase.SetError(textBox6, "textBox6 Cann't be Zero Length");
}
if (textBox7.Text.Length == 0)
{
errprvBase.SetError(textBox7, "textBox7 Cann't be Zero Length");
}
}
设置窗体的
ActiveControl
属性
public ErrorProvider mProvider;
public void SetError(Control ctl, string text)
{
if (string.IsNullOrEmpty(text)) mErrors.Remove(ctl);
else if (!mErrors.Contains(ctl)) mErrors.Add(ctl);
mProvider.SetError(ctl, text);
ActiveControl = ctl;
}
如果要将控件添加到错误列表中,是否可以设置焦点
public void SetError(Control ctl, string text)
{
if (string.IsNullOrEmpty(text))
{
mErrors.Remove(ctl);
}
else if (!mErrors.Contains(ctl))
{
mErrors.Add(ctl);
ctl.Focus();
}
mProvider.SetError(ctl, text);
}
但我认为唯一正确的方法是,在调用导致重复调用SetError()
的方法之前,可以使用一个布尔标志字段,将其设置为false
我的意思是这样的:
private boolean _isFirstError;
在开始验证set\u isFirstError=true
之前,然后在SetError()
中:
窗体上没有ActiveControl属性?如果它是Systems.Windows.Forms.Form子代,那么肯定存在.System.Windows.Forms命名空间。这段代码来自哪个类?它是表单还是其他形式?单击按钮时,我正在检查任何控件的文本是否为空。如果全部为空,则我向所有控件显示错误提供程序,但我想向第一个控件显示焦点,哪个错误提供程序首先设置错误什么是“mErrors”!?
public void SetError(Control ctl, string text)
{
if (string.IsNullOrEmpty(text))
{
mErrors.Remove(ctl);
}
else if (!mErrors.Contains(ctl))
{
mErrors.Add(ctl);
if (_isFirstError)
{
_isFirstError = false;
ctl.Focus();
}
}
mProvider.SetError(ctl, text);
}