首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为错误提供程序在C#中命中的第一个控件指定focus()?

如何为错误提供程序在C#中命中的第一个控件指定focus()?
EN

Stack Overflow用户
提问于 2013-05-24 09:46:41
回答 2查看 1.5K关注 0票数 0

在表单中,我有一个12个控件。(所有控件都应该填充一些数据),如果用户想要保存,则不向控件输入任何文本,我将向所有控件显示ErrorProviders。请输入数据。我在给你看密码

代码语言:javascript
复制
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方法。

点击按钮,我就调用这个方法

代码语言:javascript
复制
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");
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-24 09:53:04

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

代码语言:javascript
复制
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);
}

但是,我认为正确做到这一点的唯一方法是,在调用导致重复调用false的方法之前,可以使用一个布尔标志字段,该字段可以设置为SetError()

我的意思是这样的:

代码语言:javascript
复制
private boolean _isFirstError;

在您开始验证set _isFirstError = true之前,然后在SetError()

代码语言:javascript
复制
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);
}
票数 1
EN

Stack Overflow用户

发布于 2013-05-24 09:51:42

设置窗体的ActiveControl属性。

代码语言:javascript
复制
    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;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16732075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档