【问题标题】:Can any one tell me diffrence between below error provider code?谁能告诉我以下错误提供程序代码之间的区别?
【发布时间】:2014-03-20 23:53:12
【问题描述】:

IDE:Visual Studio 2010、C# .net 应用程序、winforms

我真的很惊讶这段代码 Code-1 运行良好

    ErrorProvider ef = new ErrorProvider();
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text == string.Empty)
        {
            ef.SetError(textBox1, "asdf");
        }
        else
        {
            ef.Clear();
        }
    }

但是这段代码代码2

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        ErrorProvider ef = new ErrorProvider(); //changes is here
        if (textBox1.Text == string.Empty)
        {
            ef.SetError(textBox1, "asdf");
        }
        else
        {
            ef.Clear();
        }
    }

不工作,即它没有为我提供错误处理工具。谁能告诉我这两个代码之间有什么区别的确切原因。以及为什么第二个代码不能正常工作..

【问题讨论】:

  • 看起来 ErrorProvider 在另一个地方被评估。你创建了一个局部变量,它隐藏了一个潜在的成员 ef 并在你的方法离开后丢失。

标签: c# .net winforms


【解决方案1】:

code1 中,您在事件处理程序范围之外创建 ef 对象,这样ef 对象在事件处理后仍然存在,如 code2 一旦事件被处理,ef 对象就会被销毁。

【讨论】:

  • 所以如果我将这段代码移动到一个函数中,那么这段代码会起作用吗..?我从 text_changed 事件中调用此函数 private void HandleErrorProvider() { ErrorProvider ef = new ErrorProvider(); if (textBox1.Text == string.Empty) { ef.SetError(textBox1, "asdf"); } 其他 { ef.Clear(); } } } }
  • @yogeshkmrsoni 为什么不希望 errorProvider 成为 Form 的一个字段?这就是“通常”的方式!见 msdn :msdn.microsoft.com/fr-fr/library/…
  • yogeshkmrsoni 我建议您阅读有关对象的寿命以及它们何时被破坏的信息。我想它会消除你的困惑。
  • @Raphaël Althaus 没有具体原因,只是想知道为什么它不起作用。但是 GregoryHouseMD 已经消除了我的疑虑。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-08-24
  • 2023-02-07
  • 2012-09-25
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
相关资源
最近更新 更多