【问题标题】:Reset a form to its original state with a button使用按钮将表单重置为其原始状态
【发布时间】:2015-03-11 10:36:02
【问题描述】:

我创建了一个新按钮来重置由
组成的表单 组合框,
文本框,
富文本框,
禁用按钮

所以,我创建了一个实用程序.cs 类,但它不工作并给出错误。

错误:找不到类型或命名空间名称“ComboBox”。

namespace example
{
class Utilities
{
    public static void ResetAllControls(Mainform form)
    {
        foreach (Mainform control in form.Controls)
        {
            if (form is ComboBox)
            {
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
            }
        }
    }

}

}

【问题讨论】:

  • 你有using System.Windows.Forms吗?

标签: c# winforms controls reset


【解决方案1】:

您正在尝试访问 Form 类之外的 ComboBoxComboBox 定义在 System.Windows.Forms 命名空间中,因此您需要使用 System.Windows.Form 添加。

using System.Windows.Forms; //You need this statement.
namespace example
{
 class Utilities
 {
    public static void ResetAllControls(Mainform form)
    {
        foreach (Mainform control in form.Controls)
        {
            if (form is ComboBox)
            {
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
            }
        }
    }    
 }
}

编辑

如果Utilities类不在WinForms项目中,则需要添加对System.Windows.Forms的引用,本文Add or Remove References By Using the Add Reference Dialog Box将指导您添加引用。

【讨论】:

  • 不工作...它显示错误为错误:无法将类型'example.Mainform'转换为'System.Windows.Forms.ComboBox'
  • 检查我更新的答案,我认为您还需要添加 dll。
  • 不应该是 foreach(Control control in form.Controls 吗?如果 (control is ComboBox ) ?另外,如果您希望将其作为单独的 util 类,它需要是公共的,我会将 Form 作为可重用性参数的类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
相关资源
最近更新 更多