繁体   English   中英

如何将focus()赋予错误提供程序在C#Windows应用程序中命中的第一个控件?

[英]How to give focus() to the first control that Error Provider hits in C# Windows Application?

在表格中,我有12个控件。 (所有控件都应填充一些数据)如果用户要保存 ,则无需在控件中输入任何文本,而是向所有控件显示ErrorProviders。 说请输入数据。 我正在显示代码

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()设置为第一个SetErrorSetError方法的控件。

单击按钮时,我正在调用此方法

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");
    }
}

如果要将控件添加到错误列表中,可以设置焦点吗?

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 _isFirstError = true ,然后在SetError()

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);
}

设置窗体的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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM