Search code examples
c#winformsfocuscontrolserrorprovider

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


In a Form i have a 12 Controls. (All Controls should be filled up with some Data) Without entering any text to the controls if the user wants to SAVE, I am showing the ErrorProviders to all my controls. Saying Please Enter the Data. I am showing the Code

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

If the Control has Empty data, I am passing control information and Error text to the SetError Method. I want to set the focus() to the first Control which Hits this SetError Method.

On Button Click, I am calling this method

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

Solution

  • Can you just set the focus if you are adding the control to the errors list?

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

    But I think the only way to do this properly is if you can use a boolean flag field that you can set to false just before you call the method that causes SetError() to be called repeatedly.

    I mean something like this:

    private boolean _isFirstError;
    

    And just before you start verifying set _isFirstError = true and then in 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);
    }